0

Is there are a way to compare sets as a value in JS?

> a = new Set([1])
{}
> b = new Set([1])
{}
> a == b
false
> a === b
false

but actually I expect that these two sets are equal because they contain the same elements

kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • I don't ask about an object in general. I ask how to determine the equality of Sets. I guess a Set is intended for comparison. How to determined that two sets contain the same elements? – kharandziuk Oct 25 '15 at 09:53
  • Sets are *not* "intended for comparison". The solution is exactly the same as in the duplicate. – JJJ Oct 25 '15 at 09:59
  • I don't need to compare references. I need to compare the elements – kharandziuk Oct 25 '15 at 10:04
  • Give your `Set` class a comparer method, then it should be possible. – Nina Scholz Oct 25 '15 at 10:06
  • 1
    You can write a small utility function : `function compareSets(set1, set2) { for (let value of set1.values()) { if (!set2.has(value)) return false; } return true; }`. – Shanoor Oct 25 '15 at 10:10
  • @ShanShan That won't work if set2 has more values than set1. – JJJ Oct 25 '15 at 10:12
  • 1
    Why not? Sets only contains unique values. – Shanoor Oct 25 '15 at 10:13
  • 1
    @ShanShan Try it with `new Set([1,2])` and `new Set([1,2,3])`. Your function loops through the first set, finds that both elements exist in the second set, and returns true. – JJJ Oct 25 '15 at 10:16
  • 1
    You're right, it needs a check before the loop `if (set1.size != set2.size) return false;`. This question shouldn't be flagged as duplicate, a Set is not a plain old object, none of the answers on the other question are applicable. – Shanoor Oct 25 '15 at 10:19
  • In this case, there's no such thing as "Sets", it's just a function with then name `Set`, and it returns an object, hence a duplicate. – adeneo Oct 25 '15 at 10:22
  • It's part of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – Shanoor Oct 25 '15 at 10:23
  • 1
    @ShanShan - I know, and it's just a function that returns objects that are collections of values, hence comparing is the same thing as a regular object, but if you think you have a special answer just for Sets, I'll remove the duplicate. Good luck ! – adeneo Oct 25 '15 at 10:24
  • When even [1] != [1] one should need to write a function for "comparing" arrays as well. And does the need of the OP stop there? Should [[1],[2]] == [[1],[2]] ? This leads to deeper and deeper comparisons. – trincot Oct 25 '15 at 10:41

0 Answers0