How to remove an element from an array
Short answer
The filter() method creates a new array without the unwanted value:
const colors = ['red', 'green', 'blue'];
console.log(colors.filter((color) => color !== 'green').join(', '));Output:
red, blueBy index
splice() removes elements from the array itself: the first argument is the index, the second how many elements to remove.
const colors = ['red', 'green', 'blue'];
colors.splice(1, 1);
console.log(colors.join(', '));Output:
red, blueThe first or the last element
shift() removes the first element, pop() the last:
const numbers = [1, 2, 3, 4];
numbers.shift();
numbers.pop();
console.log(numbers.join(', '));Output:
2, 3By value, the first occurrence
Find the index with indexOf() and remove one element with splice():
const items = ['a', 'b', 'a', 'c'];
const index = items.indexOf('a');
if (index !== -1) items.splice(index, 1);
console.log(items.join(', '));Output:
b, a, cCommon mistake
The delete operator does not remove an element from an array: it leaves an empty slot, and the length stays the same:
const colors = ['red', 'green', 'blue'];
delete colors[1];
console.log(colors.length, colors[1]);Output:
3 undefinedFunctions used in this recipe
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.splice — Removes, replaces or inserts elements in the middle of an array.
- Array.prototype.indexOf — Finds a value in an array and returns its index.