Search code examples
javascriptsetecmascript-6

comparing ECMA6 sets for equality


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?


Solution

  • Try this:

    const eqSet = (xs, ys) =>
        xs.size === ys.size &&
        [...xs].every((x) => ys.has(x));
    
    const ws = new Set([1, 2, 3]);
    const xs = new Set([1, 3, 2]);
    const ys = new Set([1, 2, 4]);
    const zs = new Set([1, 2, 3, 4]);
    
    console.log(eqSet(ws, xs)); // true
    console.log(eqSet(ws, ys)); // false
    console.log(eqSet(ws, zs)); // false