Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 97019  / 9 Years ago, tue, june 30, 2015, 12:00:00

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?


More From » set

 Answers
17

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




[#65989] Saturday, June 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhiannab

Total Points: 370
Total Questions: 98
Total Answers: 100

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;