Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 24, 2021 09:06 am GMT

Remove multiple item from an array in JavaScript.

Array filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let's see an example.

JavaScript array filter method

The above filter method will call the predicate() for each element of the array and constructs a new array of all the values for which predicate() returns a value that coerces to true.

In our case it will return all the values where the element is not equal 2.

Remove single item

Now let's start with a simple problem. First we need to remove a single item from an array.

Let's create a function call removeItem which will take 2 arguments. The first argument will be an array from which we will remove an item and the second argument will be the item we want to remove from the array.

Our predicate function will test all the element from the array and if the element !== to the value we provided it will constructs a new array using the passed values.

If you look at the console, you will see that we have got the expected result.

remove single item from array

Remove multiple item

Before removing multiple elements we have to explore another array method called includes().

The array includes() method determines whether an array includes a certain value among its elements, returning true or false as appropriate.

Alt Text

Now using filter() and includes() method we can remove multiple item from an array.

Let's rewrite our removeItem function to removeItems.

Removing multiple item from array

As you can see we have changed our predicate function to this: !itemsToRemove.includes(v). The predicate will return true if the value not exist in itemsToRemove array.

In this way we can remove multiple item from the array.


Original Link: https://dev.to/prosenghosh25/remove-multiple-item-from-an-array-in-javascript-2eei

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To