How to delete a value from an array

This classic question pops up once in a while. Even the creator of Node.js Ryan Dahl asked this question from the audience during his Node.js presentation (an excellent one by the way).

How do I remove an element from an array?

Is the delete operator of any use? There also exists funny named splice() and slice() , what about those? I want to modify the array in-place.

Use splice() to remove arbitrary item

The correct way to remove an item from an array is to use splice(). It takes an index and amount of items to delete starting from that index.

1 > var array = ["a", "b", "c"];
2 > var index = 1;
3 > array.splice(index, 1);
4 [ 'b' ]
5 > array;
6 [ 'a', 'c' ]

Don't confuse this with its similar cousin slice() that is used to extract a section of an array.

Use shift() and pop() if removing from the ends

If you're always interested in removing the first or the last item then you have an alternative solution. The methods shift() and pop() exist precisely for this purpose.

1 > var array = ["a", "b", "c"];
2 > array.shift();
3 'a'
4 > array;
5 [ 'b', 'c' ]
1 > var array = ["a", "b", "c"];
2 > array.pop();
3 'c'
4 > array;
5 [ 'a', 'b' ]

Using delete creates empty spots

What ever you do, don't use delete to remove an item from an array. JavaScript language specifies that arrays are sparse, i.e. they can have holes in them.

Using delete creates these kind of holes. It removes an item from the array but it does not update the length property. This leaves the array in a funny state that is best avoided.

1 > var array = ["a", "b", "c"];
2 > delete array[1];
3 > array;
4 [ 'a', , 'c' ]
5 > array.length
6 3

Notice the empty spot and unchanged length.

Remember this

The next time you need to remove something from an array, keep the following in mind.

Remove?
An item array.splice(index, 1)
First item array.shift()
Last item array.pop()
What about delete? Try to avoid delete, causes sparse arrays.
JavaScript methods for removing an element from an array
Asynchronous calls - the surest way
to get lost with Node.js
Asynchronous Call Tree
What if you could turn any spec into working code?
GET FREE LESSON
Share article: