Categories
JavaScript Answers

How to remove all elements contained in another array with JavaScript?

Spread the love

To remove all elements contained in another array with JavaScript, we use the filter and includes method.

For instance, we write

const myArray = ["a", "b", "c", "d", "e", "f", "g"];
const toRemove = ["b", "c", "g"];
const newArray = myArray.filter((el) => {
  return !toRemove.includes(el);
});

to call myArray.filter with a callback that calls toRemove.includes with the el element being iterator through to return an array with the myArray entries that aren’t in toRemove.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *