Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  126] [ 3]  / answers: 1 / hits: 120843  / 15 Years ago, thu, november 12, 2009, 12:00:00

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:




  • Gecko-specific tricks are okay

  • I'd prefer sticking to native functions (but I am open to a lightweight library if it's way faster)

  • I've seen, but not tested, JS.Set (see previous point)



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.


More From » arrays

 Answers
58

I don't know if this is most effective, but perhaps the shortest:




var A = [1, 2, 3, 4];
var B = [1, 3, 4, 7];

var diff = A.filter(function(x) {
return B.indexOf(x) < 0;
});

console.log(diff); // [2]




Updated to ES6:




const A = [1, 2, 3, 4];
const B = [1, 3, 4, 7];

const diff = A.filter(x => !B.includes(x));

console.log(diff); // [2]




[#98328] Monday, November 9, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wilson

Total Points: 27
Total Questions: 93
Total Answers: 93

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
wilson questions
Tue, Aug 9, 22, 00:00, 2 Years ago
Wed, May 11, 22, 00:00, 2 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Wed, May 13, 20, 00:00, 4 Years ago
;