Remove Item From Array by Value in JavaScript

In this tutorial, we will go through how to use the splice() and filter() functions to remove items from an array by their value in JavaScript.

 

Remove Item from JavaScript Array by Value Using the splice() Function

The JavaScript splice() function removes indexes from arrays. To remove an item from an array by value, we will first find the index of the value using the indexOf() function then pass it to the splice() function.

 

var array = ['a', 'b', 'c'];

var index = array.indexOf('b');
if (index !== -1) {
   array.splice(index, 1);
}
console.log(array);
['a', 'c']

 

The if logic in the example above is to check if the value is in the array. If indexOf() is unable to find the specified item it will return -1.

 

Note - indexOf() will only find the index of the first match. To remove all matches from the array use the filter() example below.

 

Remove Item from JavaScript Array by Value Using the filter() Function

The JavaScript filter() function loops through an array and runs a function on each item. The function for the filter will return the item if it is not equal to a value. The end result is a new array in the same order as the original without adding items with a specific value to it.

 

var array = ['a', 'b', 'c'];

var res = array.filter((f) => { return f !== 'b'});

console.log(res);
['a', 'c']

 

Conclusion

I prefer the filter() method over the indexOf() and splice() method. indexOf() will only find the first match of a value whereas the filter() function will remove all indexes containing a specific value. It is also cleaner to write, especially when used with an anonymous function.