Removing an item from a JavaScript Array

Published Monday, January 11, 2021

Jonas Arnklint
@arnklint

You have a list, an array, with some items and you want to remove one or multiple of them. The easiest way to do this is to use the .filter function on the array, to filter the items based on conditions.

Removing item indexed at n

Filter an array based on the index of the items you want to filter. The filter callback function takes three arguments. The first is the item value itself, the second is optional and is the index of that item in the array. The third just returns the original array. This means that you can use the second argument to filter a JavaScript array by index. Like this;

this is my code 392

The filter function returns a new array with only those items that the filter function returned true for.

Return true if the item is at a certain index.

Removing item that matches a condition

The same way, you can use filter to remove items that matches a condition. Like in this example, where we have a list of user objects and each object contains name and age and we only want to keep user objects where age is above 18:

This way you can filter an array based on attributes of the objects in it.

this is my code 393

You can choose to use multiple conditions to filter as well:

this is my code 394

Remove last or first item in an array, the mutable way

When removing the first or last item from an array you'll benefit from using simpler functions for that. The shift function modifies the original array by removing the first item and returning that item. The pop function does the same but removing the last item. Both of these functions modifies the array in an mutable fashion, meaning they modify the original array. Using the filter function we never mutate the original array but rather return a new modified array. This is called immutability and you should always be aware of when you are using any function of push, pop, splice, shift, unshift, reverse and sort the original array is modified. This may result in different results depending on context if for example the array is bound to something.

this is my code 395
this is my code 396

Of course you can use the filter function and remove items at an index as shown above.

Modifying different data structures is central to programming. This guide has tought you to modify arrays by removing items in different ways.

// test