There are already answers here, but here's my pure JS implementation. I'm not sure if it's optimal, but it sure is transparent, readable, and simple.
// Does array a contain elements of array b?
const contains = (a, b) => new Set([...a, ...b]).size === a.length
const isEqualSet = (a, b) => contains(a, b) && contains(b, a)
The rationale in contains()
is that if a
does contain all the elements of b
, then putting them into the same set would not change the size.
For example, if const a = [1,2,3,4]
and const b = [1,2]
, then new Set([...a, ...b]) === {1,2,3,4}
. As you can see, the resulting set has the same elements as a
.
From there, to make it more concise, we can boil it down to the following:
const isEqualSet = (a, b) => {
const unionSize = new Set([...a, ...b])
return unionSize === a.length && unionSize === b.length
}