Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, blue

By 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, blue

The 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, 3

By 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, c

Common 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 undefined

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.