JavaScript: Remove all occurrences of a value from an array

Updated: March 17, 2023 By: Khue Post a comment

When working with JavaScript arrays, there might be cases where you need to delete all elements that match a particular value and leave behind only the elements that do not match that value. This concise, practical article shows you a couple of different ways to achieve this goal.

Using the filter() method

This approach is short and elegant. It is a kind of single-line solution. In the following example, we’re going to remove all occurrences of 2 from a given array named arr:

const arr = [2, 3, 4, 2, 1, 9, 8, 2, 3, 2, -2, 0];
const val = 2;

let newArr = arr.filter((element) => element !== val);
console.log(newArr);

Output:

[3, 4, 1, 9, 8, 3, -2, 0]

Using the splice() method

We can also use the splice() method in combination with a for loop to get the job done.

Example:

const arr = [2, 3, 4, 2, 1, 9, 8, 2, 3, 2, -2, 0];
const val = 2;

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === val) {
    // Remove one element at index i
    arr.splice(i, 1);
    // Decrement i to avoid skipping elements
    i--;
  }
}
console.log(arr);

Output:

[3, 4, 1, 9, 8, 3, -2, 0]

Instead of a for loop, we can use a while loop and the indexOf() method to find and remove the value from the array until it is not found:

const arr = [2, 3, 4, 2, 1, 9, 8, 2, 3, 2, -2, 0];
const val = 2;

// Find the first index of val
let index = arr.indexOf(val);

while (index !== -1) {
  // While val is found in the array
  // Remove one element at index
  arr.splice(index, 1);

  // Find the next index of val
  index = arr.indexOf(val);
}
console.log(arr);

The result will be the same. However, this code is more verbose and less efficient.