Let A
and B
be two sets. I'm looking for really fast or elegant ways to compute the set difference (A - B
or A \B
, depending on your preference) between them. The two sets are stored and manipulated as Javascript arrays, as the title says.
Notes:
Edit: I noticed a comment about sets containing duplicate elements. When I say "set" I'm referring to the mathematical definition, which means (among other things) that they do not contain duplicate elements.
if don't know if this is most effective, but perhaps the shortest
A = [1, 2, 3, 4];
B = [1, 3, 4, 7];
diff = A.filter(function(x) { return B.indexOf(x) < 0 })
console.log(diff);
Updated to ES6:
A = [1, 2, 3, 4];
B = [1, 3, 4, 7];
diff = A.filter(x => !B.includes(x) );
console.log(diff);