Categories
JavaScript Answers

How to compare 2 arrays which returns difference with JavaScript?

Spread the love

To compare 2 arrays which returns difference with JavaScript, we use the filter and indexOf methods.

For instance, we write

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

to call b.filter with a callback that calls a.indexOf with i to see if i isn’t included in a by checking if indexOf returns -1.

An array with the items in b that’s not in a is returned.

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 *