How to Compare ES6 Sets for Equality?

John Au-Yeung
2 min readMar 18, 2023
Photo by Igor Starkov on Unsplash

Sometimes, we want to compare 2 JavaScript sets to see if they have the same content.

In this article, we’ll look at how to compare 2 JavaScript sets to see if they have the same content.

Compare ES6 Sets for Equality

We can compare ES6 sets for equality by looping through its contents and check if any element in one set is missing in the other and check that their sizes are equal.

For instance, we can write:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 2]);
const eqSet = (as, bs) => {
if (as.size !== bs.size) {
return false;
}
for (const a of as) {
if (!bs.has(a)) {
return false;
}
}
return true;
}
console.log(eqSet(a, b));

We created the a and b sets which we want to compare.

Then we create the eqSet function with the as and bs parameters which are sets.

In the function, we compare is as and bs have different sizes. If they don’t then we return false .

Then if they have the same size, we loop through the as set with the for-of loop.

In the loop body, we check if bs is missing any items in as .

If something is missing, we return false .

If the loop is finished then we return true since both sets have the same size and has all the same elements.

Therefore, the console log should log true .

Conclusion

We can compare ES6 sets for equality by looping through its contents and check if any element in one set is missing in the other and check that their sizes are equal.

--

--