How to remove a specific item from an array in JavaScript?

By Gulshan Saini
Published in JavaScript
January 04, 2021
1 min read

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.

Watch on YouTube

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 fruits array.

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"]


Previous Article
How to redirect http url request in server?

Related Posts

How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media