Categories
JavaScript Answers

How to compare JavaScript sets for equality?

Spread the love

Sometimes, we want to compare JavaScript sets for equality.

In this article, we’ll look at how to compare JavaScript sets for equality.

How to compare JavaScript sets for equality?

To compare JavaScript sets for equality, we can check if 2 sets have all the same entries and have the same size.

For instance, we write

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 2]);

const areSetsEqual = (a, b) =>
  a.size === b.size && [...a].every((value) => b.has(value));

console.log(areSetsEqual(a, b));

to create 2 sets a and b.

And then we check if both sets are equal with the areSetEqual function.

In it, we check if both have the same size with

a.size === b.size 

Then we convert a to an array with the spread operator and call every on the array with a callback that check if a has all the same entries as b with has.

If they have the same size and the same entries, then they’re the same since sets can’t have duplicate values.

Conclusion

To compare JavaScript sets for equality, we can check if 2 sets have all the same entries and have the same size.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *