Array difference
JavaScript, Array · Oct 19, 2020

Calculates the difference between two arrays, without filtering duplicate values.
- Create a
Set
fromb
to get the unique values inb
. - Use
Array.prototype.filter()
ona
to only keep values not contained inb
, usingSet.prototype.has()
.
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
difference([1, 2, 3, 3], [1, 2, 4]); // [3, 3]