We are required to write a function that takes in an array of numbers and a number, and it should remove all the occurrences of that number from the array inplace.
Let’s write the code for this function.
We will make use of recursion to remove elements here. The recursive function that removes all occurrences of an element from an array can be written like.
Example
const numbers = [1,2,0,3,0,4,0,5]; const removeElement = (arr, element) => { if(arr.indexOf(element) !== -1){ arr.splice(arr.indexOf(element), 1); return removeElement(arr, element); }; return; }; removeElement(numbers, 0); console.log(numbers);
Output
The output in the console will be −
[ 1, 2, 3, 4, 5 ]