avatarKitson Broadhurst

Summary

The web content provides guidance on two methods for removing elements from an array in JavaScript: using Array.filter() for an immutable approach and Array.splice() for mutable array manipulation.

Abstract

The article "How to remove an element from an array in JavaScript" addresses a common JavaScript task by presenting two primary methods for element removal from arrays. The first method utilizes Array.filter() to create a new array that excludes the specified element(s), leaving the original array unchanged. This method is particularly useful when a mutable operation is required. The second method, Array.splice(), directly modifies the original array by removing the element(s) at a specified index, and it can also replace elements during the removal process. The article emphasizes the importance of browser compatibility, noting that arrow functions and Array.includes() used in the filter() method are not supported in Internet Explorer or older browsers, suggesting BabelJS as a solution for compatibility issues. Additionally, the article highlights the potential to access and utilize the removed elements when using splice().

Opinions

  • The author suggests that Array.filter() is a good choice for removing elements without mutating the original array.
  • There is a clear preference for Array.filter() when the immutability of the original array is desired.
  • The author warns about the lack of support for certain features in older browsers, implying that developers should be mindful of their target audience's browser usage.
  • The use of Array.splice() is recommended for scenarios where the original array can be mutated, and there is a need to remove elements by their index.
  • The article conveys that Array.splice() is versatile as it allows for the replacement of removed elements, which can be beneficial in certain use cases.
  • The author values the ability to work with the elements that have been removed from an array, as demonstrated with the splice() method's return value.

How to remove an element from an array in JavaScript

Two ways to quickly remove an element from an array in JavaScript

So you want to remove an item from an array in JavaScript?

Well, you’re not alone!

It’s one of the most upvoted JavaScript questions on stack overflow and can feel a little unnatural considering how simple it is to array.push().

Method 1 — remove an element with Array.filter()

If you want to remove an element while leaving the original array intact (unmutated) then filter() is a good choice!

Removing a single element:

const itemToRemove = 3
const originalArray = [2, 51, 3, 44]
const newArray = originalArray.filter(item => item !== itemToRemove)
console.log(newArray) // [2, 51, 44]
console.log(originalArray) // [2, 51, 3, 44]

Breaking that down.

We define a variable newArray and set it equal to the return value of our array filter. Inside of our filter, we pass an ECMAScript 6 arrow function.

This function tests each item in the array and returns:

  • true if the item does not match the itemToRemove
  • false if the item matches the itemToRemove

Removing multiple items:

const toDelete = [5, 6, 7, 8]
const original = [1, 5, 6, 7, 8]
const new = original.filter( item => !toDelete.includes(item) )
console.log(new) // [1]
console.log(original) // [1, 5, 6, 7, 8]

We follow the same method to filter our array, but this time, we test that each item is NOT included in our toDelete array.

WARNING: there is no support in Internet Explorer or older web browsers for arrow functions and Array.includes(). If you have to support these browsers consider Method 2 OR take a look at BabelJS.

Method 2 — remove an element using Array.splice()

The Array.splice() method allows us to remove any type of element from an array e.g. numbers, strings, objects, booleans etc.

const arrayOfThings = [1, "two", {three: 3}, true]

To remove something from an array with the splice() method, we need to provide two things:

  1. the element index (beginning at index 0)
  2. the number of elements we want to remove
arrayOfThings.splice(startIndex, numberToRemove)

This means we must first figure out which position in the array our element is.

For that, we’ll use the indexOf() method:

const index = arrayOfThings.indexOf("two")

Note thatindexOf() returns -1 for elements which don’t exist.

Putting it all together:

const arrayOfThings = [1, "two", {three: 3}, true]
// calculate the position of the item
const index = arrayOfThings.indexOf("two")
if (index > -1) {
  arrayOfThings.splice(index, 1)
}
console.log(arrayOfThings) // [1, {three: 3}, true]

WARNING: this method removes the first instance of the item as indexOf() returns the index of the first matching item it finds.

splice() Bonus 1 — using the element you have removed

The splice() method does not return the original array but mutates it.

This means that if we were to assign the return result to a variable, it would not be the original array with the object removed, but an array containing the removed object(s).

const originalArray = [2, 5, 9]
// remove one element from index 2
const returnValue = originalArray.splice(2, 1)
console.log(returnValue) // [9]
console.log(originalArray) // [2, 5]

When we console.log the original array, it has been mutated removing the element at index 2.

We now have access to the removed element(s) array in our returnValue variable.

splice() Bonus 2 — replace the removed element

The splice() method can do more than just remove items from an array.

It also allows you to replace the item you’re removing with one (or more) items:

array.splice(startIndex, numberToRemove, itemToAdd, itemToAdd2, ...)

This means that if we want to both remove AND replace an item, we simply:

const arrayOfThings = [1, 2, 9, 4, 5]
// calculate the position of the item
const index = arrayOfThings.indexOf(9)
if (index > -1) {
  // remove one item from our index and replace it with 3
  arrayOfThings.splice(index, 1, 3)
}
console.log(arrayOfThings) // [1, 2, 3, 4, 5]

In summary, we can use Array.filter() or Array.splice() to remove items from our arrays.

Array.filter() leaves the original array unmutated, while Array.splice() mutates the original array and returns the removed element(s).

Resources

JavaScript
Arrays
Programming
Technology
Software Engineering
Recommended from ReadMedium