Categories
JavaScript Answers

How to compute a set difference using JavaScript arrays?

Spread the love

To compute a set difference using JavaScript arrays, we use the filter method.

For instance, we write

const a = [1, 2, 3, 4];
const b = [1, 3, 4, 7];

const diff = a.filter((x) => {
  return b.indexOf(x) < 0;
});

console.log(diff);

to call a.filter with a callback that checks if the item x in a isn’t in b with b.indexOf(x) < 0.

An array with the items in a but not in b is then 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 *