In this tutorial, I am going to show you a very simple, fast, and modern(ES6) way to remove a specific element from an array using
Array.prototype.filter() method and fat arrow function.
Array.prototype.filter() method creates a new array with all elements that pass the test implemented by the provided function.
Old way: Earlier the approach was to find the index of the array element you want to remove using
Array.prototype.indexOf()method, and then remove that index with splice.
Let’s say you have an
array of fruits
let fruits = ['apple', 'banana', 'kiwi', 'grapes']
And, you want to the remove “kiwi” element from the
To remove “kiwi” from
fruits array, we are going to use
Array.filter() method as follows
let fruits = ['apple', 'banana', 'kiwi', 'grapes'] fruits = fruits.filter((fruit) => fruit !== 'kiwi')
Following line, removes the item “kiwi” from from array and create new array which we assign back to fruits array.
fruits = fruits.filter((fruit) => fruit !== 'kiwi')
Notice how we used ES6 fat arrow anonymous function
fruit => fruit !== "kiwi", which test the condition and return the results
Now, if you console.log the
fruits array, you will see the
fruits array no more contains the item “kiwi”
let fruits = ['apple', 'banana', 'kiwi', 'grapes'] // remove kiwi from fruits array fruits = fruits.filter((fruit) => fruit !== 'kiwi') console.log(fruits) // Output: ["apple", "banana", "grapes"]