Remove element from a JavaScript array by value

OpenJavaScript 0
Reading Time: 1 minute 🕑

Last updated: April 12, 2022.

There is as yet no method designed for the specific purpose of removing an array element by its value in JavaScript.

Instead, the .splice() and .filter() methods can be utilized for this purpose.

Which one you should employ depends upon whether you want to modify (‘mutate’) the original array or create a new one.

With mutation: splice

The splice method requires two arguments: (i) the index of an array element and (ii) how many elements should be removed from the array.

You can therefore use splice to remove an array element by its value by specifying the index of the value as a first argument and 1 as the second.

To pass in the index of the value as first argument, use .indexOf(), which returns the index value of the value passed into it:

/* Removing array element with mutation using .splice() */

const animals = ["🐶","🐱","🐭","🐹","🐰","🦊"];

animals.splice(animals.indexOf("🐹"), 1);

console.log(animals); // ["🐶","🐱","🐭","🐰","🦊"]

Without mutation: filter

If you want to retain a copy of the original array, use the filter method instead.

The filter method accepts a function which is executed for each element in the array. If it returns the value true, the element is included in the new array it produces; if false, it is filtered out.

So to filter an individual element, you run a check to see if each item does not equal to the one you want to filter. Only the one you want to filter will return false and thus not be included in the new array:

/* Removing array element without mutation using .filter() */

const animals = ["🐶","🐱","🐭","🐹","🐰","🦊"];

const animalsFiltered = animals.filter((item) => item !== "🐹");

console.log(animalsFiltered); // [ "🐶","🐱","🐭","🐰","🦊"]
console.log(animals); // ["🐶","🐱","🐭","🐹","🐰","🦊"]

Related links