Categories
JavaScript Answers

How to find elements in array that are not in another array with JavaScript?

Spread the love

Sometimes, we want to find elements in array that are not in another array with JavaScript.

In this article, we’ll look at how to find elements in array that are not in another array with JavaScript.

How to find elements in array that are not in another array with JavaScript?

To find elements in array that are not in another array with JavaScript, we use the filter and includes method.

For instance, we write

const a1 = ["a", "b", "c", "t"];
const a2 = ["d", "a", "t", "e", "g"];

console.log(a2.filter((x) => !a1.includes(x)));

to call filter with a callback that checks if item x in a2 isn’t a1 with includes and negation.

An array with the items in a2 not in a1 is returned.

Conclusion

To find elements in array that are not in another array with JavaScript, we use the filter and includes method.

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 *