How to remove certain number elements from an array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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.


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);
removeElement(numbers, 0);


The output in the console will be −

[ 1, 2, 3, 4, 5 ]
Published on 21-Aug-2020 18:03:40