Categories
JavaScript Answers

How to filter an array from all elements of another array with JavaScript?

Spread the love

To filter an array from all elements of another array with JavaScript, we use the filter and includes methods.

For instance, we write

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4];
const res = arr1.filter((item) => !arr2.includes(item));
console.log(res);

to call filter with a callback that checks if the item in arr1 isn’t in arr2.

If it’s not, then it’s included in the array returned by filter.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.