Remove Elements From an Array in JavaScript

When working with arrays in JavaScript, we often need to remove elements. There are many reasons to do this and various ways to accomplish it, and in this guide I'll explain each use case and provide examples.

Here are some of the things we'll cover:

  • Removing elements by index.
  • Removing elements by value.
  • Removing elements from the beginning and end.
1

The splice function modifies an array by removing or replacing existing elements. So if we already know the index of the element we want to remove, this is easy to accomplish with splice.

Suppose we've got the following array, and we want to remove the element at index 2 (Augustine), we can use splice:

> let names = ['Athanasius', 'Augustine', 'Ignatius', 'Clement', 'Polycarp'];

> names.splice(2, 1)
[ 'Ignatius' ]

> names
[ 'Athanasius', 'Augustine' ]

This means that we want to remove one element at index two. The removed element(s) are returned, and the array is modified in place.

2

We can also use splice to remove the element by value, but first we need to loop through and find the index of the value.

> let names = [ 'Athanasius', 'Augustine', 'Ignatius', 'Augustine', 'Clement', 'Polycarp' ]

> for (let [index, name] of names.entries()) {    
      if (name === 'Augustine') {    
          names.splice(index, 1)
      }
  }

> names
[ 'Athanasius', 'Ignatius', 'Clement', 'Polycarp' ]

Notice that the name we wanted to remove exists twice in the array. The above code will remove any occurrences, and again it will modify the array in place.

3

The above example is a little verbose. Using filter we can accomplish some similar in a single line.

> let names = [ 'Athanasius', 'Augustine', 'Ignatius', 'Augustine', 'Clement', 'Polycarp' ]

> names.filter(name => name !== 'Augustine')
[ 'Athanasius', 'Ignatius', 'Clement', 'Polycarp' ]

The filter method creates a new array composed of elements that pass the "test" function. In our case, the test function simply ensures that the name is not "Augustine".

4

We can use the pop method to remove an element from the end of an array:

> let names = [ 'Athanasius', 'Augustine', 'Ignatius', 'Clement', 'Polycarp' ]

> names.pop()
'Polycarp'

> names
[ 'Athanasius', 'Augustine', 'Ignatius', 'Clement' ]

As with splice, the removed element is returned, and the array is modified in place.

5

The shift method operates exactly like pop except it removes an element from the beginning of the array.

> names = [ 'Athanasius', 'Augustine', 'Ignatius', 'Clement', 'Polycarp' ]

> names.shift()
'Athanasius'

> names
[ 'Augustine', 'Ignatius', 'Clement', 'Polycarp' ]