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?
None of these solutions bring “back” the expected functionality to a data structure such as set of sets. In its current state, the Javascript Set is useless for this purpose because the superset will contain duplicate subsets, which Javascript wrongly sees as distinct. The only solution I can think of is converting each subset to Array, sorting it and then encoding as String (for example JSON).
Solution
Basic usage
Ultimate test: set of sets
Comparing two objects with ==, ===
When using
==
or===
operator to compare two objects, you will always getfalse
unless those object reference the same object. For example:Otherwise, == equates to false even though the object contains the same values:
You may need to consider manual comparison
In ECMAScript 6, you may convert sets to arrays beforehand so you can spot the difference between them:
NOTE:
Array.from
is one of the standard ECMAScript 6 features but it is not widely supported in modern browsers. Check the compatibility table here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibilityBased on the accepted answer, assuming support of
Array.from
, here is a one-liner:The other answer will work fine; here is another alternative.
However, be aware that this does not do deep equality comparison. So
will return false. If the above two sets are to be considered equal, we need to iterate through both sets doing deep quality comparisons on each element. We stipulate the existence of a
deepEqual
routine. Then the logic would beWhat this does: for each member of s1, look for a deeply equal member of s2. If found, delete it so it can't be used again. The two sets are deeply equal if all the elements in s1 are found in s2, and s2 is exhausted. Untested.
You may find this useful: http://www.2ality.com/2015/01/es6-set-operations.html.
I follow this approach in tests :
Try this:
A more functional approach would be:
The
all
function works for all iterable objects (e.g.Set
andMap
).If
Array.from
was more widely supported then we could have implemented theall
function as:Hope that helps.