How do you compare two javascript sets? I tried using ==
and ===
but both return false.
a = new Set([1,2,3]);
b = new Set([1,3,2]);
a == b; //=> false
a === b; //=> false
These two sets are equivalent, because by definition, sets do not have order (at least not usually). I've looked at the documentation for Set on MDN and found nothing useful. Anyone know how to do this?
lodash provides
_.isEqual()
, which does deep comparisons. This is very handy if you don't want to write your own. As of lodash 4,_.isEqual()
properly compares Sets.If sets contains only primitive data types or object inside sets have reference equality, then there is simpler way
const isEqualSets = (set1, set2) => (set1.size === set2.size) && (set1.size === new Set([...set1, ...set2]).size);
1) Check if sizes are equal . If not, then they are not equal.
2) iterate over each elem of A and check in that exists in B. If one fails return
unequal
3) If the above 2 conditions fails that means they are equal.
2) Method 2
You can also try:
I created a quick polyfill for Set.prototype.isEqual()
Github Gist - Set.prototype.isEqual