Remove Elements From an Array in JavaScript

John John (304)
0

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.
Posted in these interests:
h/javascript27 guides
h/code69 guides

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.

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.

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".

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.

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' ]
Minecraft already comes with tools you can use!
Britt Britt (157)
0

Minecraft enables players to do just about anything. Throw mods, resource packs, and shaders into the mix, and Minecraft can turn in to a variety of different games.