This website collects cookies to deliver better user experience
Remove multiple item from an array in JavaScript.
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.
const array =[1,2,3,4,5];constpredicate=(v)=> v !==2;array.filter.(predicate);// [1, 3, 4, 5]
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.
constremoveItem=(array, itemToRemove)=> array.filter(v=> v !== itemToRemove);removeItem([1,2,3,4,5]);// [1, 2, 4, 5]
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.
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.