In this article, we will consider the different ways we can remove elements from a JavaScript array.

An array provides a way to hold a collection of items in one place. We can reference items one at a time in order to modify them or utilize them for something else, add new items to the array, or even remove existing items from the array when we no longer need them.

Using array.pop() to remove elements from a JavaScript array

If we need to remove elements from the end of an array, we can make use of the array.pop() method. pop() removes and returns the last item in an array.

The following example illustrates the use of this method.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']

let lastPlanet = planets.pop();
console.log("removed planet: ", lastPlanet);
console.log("Remaining planets: ", planets);

Output:

removed planet:  Pluto
Remaining planets:  [
  'Mercury', 'Venus',
  'Earth',   'Mars',
  'Jupiter', 'Saturn',
  'Uranus',  'Neptune'
]

The item removed from planets is saved in the lastPlanet variable. When lastPlanet is displayed, we get Pluto.

From the output also, we can see that pop() modifies the array so that planets now contains every other planet, except the removed planet (planets Mercury to Neptune).

Use array.shift() to remove elements from JavaScript array

The previous example removed the last item from an array.

We can also remove an element from a javascript array using array.shift(). array.shift() removes elements from the beginning of an array and returns the removed result.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']

let firstPlanet = planets.shift();
console.log("removed planet: ", firstPlanet);
console.log("Remaining planets: ", planets);

Output:

removed planet:  Mercury
Remaining planets:  [
  'Venus',   'Earth',
  'Mars',    'Jupiter',
  'Saturn',  'Uranus',
  'Neptune', 'Pluto'
]

In the example, we still made use of the planets array in its original state, with the 9 planets. The call to planets.shift() returned the first planet Mercury.

However, it did more; it also removed Mercury from the array. The console.log() call shows this since the array now contains only 8 planets beginning from Venusto Pluto.

Using array.splice() to remove elements by index

So far, our planet removal has focused on special positions in the planets array – the first position, and the last position.

What if we needed to remove a planet from an arbitrary position in the array?

For that, we will have to make use of the array method splice().

The following example illustrates how to use this method.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']

let largestPlanet = planets.splice(4, 1);
console.log("removed planet: ", largestPlanet);
console.log("Remaining planets: ", planets);

Output:

removed planet:  [ 'Jupiter' ]
Remaining planets:  [
  'Mercury', 'Venus',
  'Earth',   'Mars',
  'Saturn',  'Uranus',
  'Neptune', 'Pluto'
]

The above example made use of splice() to remove the planet at index 4 (that is Jupiter). The removal was actually a success, but what splice() returned was an array containing the removed item.

Generally, splice() returns an array of items removed. To call splice(), we need to specify the index (as we did previously), and the number of elements to remove from that position.

In the previous example, we specified the start index, and the number of items we needed to remove (1 item). We will try again to remove all the gas giants. This means we will have to remove four items, beginning from Jupiter.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
let gasGiantPlanets = planets.splice(4, 4);
console.log("removed planets: ", gasGiantPlanets);
console.log("Remaining planets: ", planets);

Output:

removed planets:  [ 'Jupiter', 'Saturn', 'Uranus', 'Neptune' ]
Remaining planets:  [ 'Mercury', 'Venus', 'Earth', 'Mars', 'Pluto' ]

The items removed were Jupiter, Saturn, Uranus, and Neptune, the largest planets in our solar system, also known as the gas giants.

But what happens when we only specify the start index? Look at the output of the next example.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']
let removedPlanets = planets.splice(4);
console.log("removed planets: ", removedPlanets);
console.log("Remaining planets: ", planets);

Output:

removed planets:  [ 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto' ]
Remaining planets:  [ 'Mercury', 'Venus', 'Earth', 'Mars' ]

Without specifying the number of items to remove, splice() removes all items from Jupiterto the last item.

Remove an element by value by using array.filter()

The previous examples removed an item by its position in the array. What if we need to remove an item by value? We can make use of Javascript’s array.filter() method to filter out the item we need to remove.


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto'];
let itemToRemove = 'Earth';
leftOverPlanets = planets.filter(data => data != itemToRemove);

console.log("removed planet: ", itemToRemove);
console.log("Remaining planets: ", leftOverPlanets);
console.log("Original planets: ", planets);

Output:

removed planet:  Earth
Remaining planets:  [
  'Mercury', 'Venus',
  'Mars',    'Jupiter',
  'Saturn',  'Uranus',
  'Neptune', 'Pluto'
]
Original planets:  [
  'Mercury', 'Venus',
  'Earth',   'Mars',
  'Jupiter', 'Saturn',
  'Uranus',  'Neptune',
  'Pluto'
]

After the filtering, a new array is returned, and the original array is unaffected ( as seen from the output). The other item removal methods modify the array but filter() does not. In addition, filter() removes all items that match the value to remove. The next example illustrates this.


let data = [12, 10, 7, 7, 13, 5, 12, 5, 11, 7, 3, 13];
let itemToRemove = 7;
leftOver = data.filter(e => e != itemToRemove);

console.log("removed num: ", itemToRemove);
console.log("Remaining data: ", leftOver);
console.log("Original data: ", data);

Output:

removed num:  7
Remaining:  [
  12, 10, 13,  5, 12,
   5, 11,  3, 13
]

All instances of 7 have been filtered out, without affecting the original data array.

Create a Remove method

The methods of removing elements from JavaScript array we explored could:

  • Remove a given item from the end of the array and return the element.
  • Remove a given item from the front of the array and return the element
  • Remove one or more items beginning from a given position and return an array of the removed items.

We could create our own JavaScript function that removes a single item from any position within an array.

Our function would simply accept the index of the element to remove and return the removed item.

In this section, we will implement such a JavaScript function.

We will call the function removeByIndex. It will be expecting two arguments:

  • The array from which to remove the item,
  • The index of the item to remove

The return value of the function will be the removed item, or undefined if the index is out of range. The function definition is shown below.


function removeByIndex(arr, index) {
    let value = undefined;

    if (index < arr.length) {
        value = arr[index];
        arr.splice(index, 1);

    }
    
    return value;  

};

The splice() method was used to implement the actual removal. This makes our function destructive since it modifies the array. We can now make use of our remove function.

Check out the next example


let planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto'];

let removeResult = removeByIndex(planets, 0);
console.log("After removing:", planets);
console.log("Item removed:", removeResult);

removeResult =  removeByIndex(planets, 9);
console.log("After removing:", planets);
console.log("Item removed:", removeResult);

Output:

After removing: [
  'Venus',   'Earth',
  'Mars',    'Jupiter',
  'Saturn',  'Uranus',
  'Neptune', 'Pluto'
]
Item removed: Mercury
After removing: [
  'Venus',   'Earth',
  'Mars',    'Jupiter',
  'Saturn',  'Uranus',
  'Neptune', 'Pluto'
]
Item removed: undefined

The first call succeeded in removing the first item from the array. The second call, however, passed an index that was out of range. Thus, our function returned undefined since it did not do any removal.

Conclusion

That’s it for our discussion on removing an element from a javascript array. If you liked this tutorial, you can check out our other programming tutorials.

You can check out How to do Exponents in Java?

Like this article? Follow us on Facebook and LinkedIn.