Remove a specific item from a Javascript array, knowing its value
There are several ways to remove a specific item from a JavaScript array, knowing its value. Let’s consider the array [1, 2, 3, 4, 5]
, and let’s try to remove the value 3
.
Method 1: Splice
The splice method is meant to add or remove an element from an array. Once the index of the element matching the target value is found — using indexOf, it can be used to remove the corresponding entry:
const array = [1, 2, 3, 4, 5]
const index = array.indexOf(3) // 2
array.splice(index, 1) // Modified in place.
Method 2: Filter
The filter method generates a new array containing all the entries that satisfy a given condition. We can remove the target element, with the right condition:
const array = [1, 2, 3, 4, 5]
const filteredArray = array.filter(item => item !=3) // New array.
Method 3: Slice
The slice method returns a copy of a portion of an array between a start and an end position. We can use it twice, around the target element, then concatenate the two outputs:
const array = [1, 2, 3, 4, 5]
const index = array.indexOf(3)
const filteredArray = array.slice(0, index).concat(array.slice(index + 1)) // New array.
Method 4: Pop (only if last item)
The pop method removes the last element from an array. Therefore, it can’t unfortunately be used to remove the number 3
, but if the item we’re trying to remove happens to be the last, then it’s straightforward:
const array = [1, 2, 3, 4, 5]
array.pop() // [1, 2, 3, 4] — Modified in place.