Codementor Events

Remove multiple item from an array in JavaScript.

Published Aug 31, 2021
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]; 
const predicate = (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.

const removeItem = (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.

const array = [1, 2, 3, 4, 5]; array.includes(1); // true

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

Let's rewrite our removeItem function to removeItems.

const removeItems = (array, itemToRemove) => { 
  return array.filter(v => { 
    	return !itemsToRemove.includes(v); 
    });
} 
removeItems([1, 2, 3, 4, 5], [1, 4]); // [2, 3, 5]

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.

Discover and read more posts from Prosen Ghosh
get started
post commentsBe the first to share your opinion
Show more replies