How to Remove Specific Items From a Javascript Array?

javascript

Items from a Javascript array can be removed by using either the index or the value of the item.

Working with the following array:

a = ["zero", "one", "two", "three"]

To remove items by index, the splice function can be used.

a.splice(2, 1); // "2" is the index to be removed, "1" indicates that one item is to be removed starting at the index "2"
console.log(a); // Output: ['zero', 'one', 'three']

To remove elements by value, find the index of the item using the indexOf function and then use splice.

idx = a.indexOf("two"); 
// idx will be the index of "two" if it exists in the array
// else, it will be -1
// Now, if idx is not -1, remove the item by index
if(idx>-1) {
  a.splice(idx, 1);
}

To remove one or more items by value from an array, use the filter function.

a = ["zero", "one", "two", "three", "one"];
a.filter(value => value!=="one");
console.log(a); // output: ['zero', 'two', 'three']

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?