Graphics Cove

Remove an item from an array

Adding elements to an array in JavaScript is easy. If you're creating a checklist for example, the user can add new items via an input on the frontend and we add them to an array with arr.push(newItem).

However, what if the user wants to remove something from the checklist? The one they want to remove might not always be the first or last, so how do we remove it?

Removing the first item in an array

To remove the first item in an array we can use shift(). This method takes everything in the array and shifts it to the left, effectively removing the first item. This method changes the length of the array.

let arr = [1, 2, 3, 4]
let firstItem = arr.shift(); // firstItem == 1
console.log(arr); // [2, 3, 4]

Removing the last item in an array

Removing the last item in the array can easily be achieved with pop(). This method changes the length of the array.

let arr = [1, 2, 3, 4]
let lastItem = arr.pop()

console.log(lastItem); // lastItem == 4
console.log(arr); // [1, 2, 3]

If you call pop() on an empty array, it returns undefined.

Removing a specific item in an array

Removing a specific item in the array doesn't have any direct methods, but is still fairly straightforward.

We need to find the index of the item in the array you want to remove by using indexOf, and then remove that index with splice().

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

let array = [1, 2, 3, 4]

const index = array.indexOf(3) // Get the index of the number 3

// Check if the item you are looking for exists before removing it
if (index > -1) {
  array.splice(index, 1)
}

console.log(array) // array = [1, 2, 4]

In the example splice() takes two arguments, the first is the index of the item we want to remove, in this case it's our variable index, the second is how many items you want to remove, in our case just the one.

Note that splice() modifies the array in place and returns a new array containing the elements that have been removed.

Removing all similar items in an array

We can extend the above splice() method to remove all of the same values by using a while loop on the array:

let i = 0
const value = 7 // Remove all the 7s from the array
while (i < arr.length) {
    if (arr[i] === value) {
        arr.splice(i, 1)
    } else {
        ++i
    }
}

© 2010 - 2023 Graphicscove

TwitterFacebookFAQsPrivacy PolicyFree Website Review