This post will discuss how to remove all instances of a given value from an array in JavaScript.

1. Using Array.prototype.filter() function

The recommended solution in JavaScript is to use the filter() method, which creates a new array with elements that pass the predicate function. The following code example shows how to remove all instances of specified values from the array.

Download  Run Code

 
Note that this solution doesn’t modify the original array but creates a new array. You can further shorten the code with ES6 arrow functions.

Download  Run Code

2. Using jQuery

Similar to the JavaScript native filter() method, jQuery Library has the grep() method. Following is a simple example demonstrating usage of this method:

Download Code

3. Using Underscore/Lodash Library

The Underscore and Lodash library have the _.without method, which returns a copy of an array excluding the specified values. Here’s a simple example that removes every instance of the given value from an array with the _.without method.

Download Code

4. Using Array.prototype.splice() function

The splice() method in JavaScript is often used to in-place add or remove elements from an array. The idea is to find indexes of all the elements to be removed from an array and then remove each element from the array using the splice() method.

Download  Run Code

5. Using delete operator

The JavaScript delete operator removes a property from an object. If called on an array arr like delete arr[i], it replaces the value present at index i with a value undefined. In other words, it leaves an empty slot at index i. This would translate to a simple code below:

Download  Run Code

That’s all about removing all instances of a value from an array in JavaScript.