How To Remove Specific Element From JavaScript Array
JavaScript
29/03/2021
JavaScript does not currently offer any built-in array method(s) to remove a specific element. However, there are two main functions that allow us to achieve the same outcome: splice
and filter
.
Splice
Using the splice
method, we first need to identify the index of an element we wish to remove, typically with indexOf
. The splice
function is then called on the array with the 1st argument being the index we'd like to start at and the 2nd argument being how many to remove.
const array = ['bananas', 'apples', 'pears']
const index = array.indexOf('apples')array.splice(index, 1) // Array [ "apples" ]
console.log(array) // Array [ "bananas", "pears" ]
You may have noticed 2 things in the code snippet above. When called, the function returns an array with the removed element. But even more importantly, it modifies the original array itself.
Filter
Unlike splice
, filter
does not alter the original array, which should make it the preferred option in my opinion. 🤓 Similarly, the function is called on the array and iterates through each element of said array. However, while iterating, each element is compared to a statement we define and is included in the new array if the statement equals to true.
const array = ['bananas', 'apples', 'pears']
const filteredArray = array.filter(item => { return item !== 'apples'})
console.log(filteredArray) // Array [ "bananas", "pears" ]
In each iteration, we simply make sure that the item of the array is not equals to apples
.