There are already answers here, but here is my pure JS implementation. I’m not sure if it’s optimal, but it 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 for contains() is that if a contains all the elements of b , then putting them in the same set will not result in a resize.
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 result set has the same elements as a .
From there, to make it more concise, we can reduce it to the following:
const isEqualSet = (a, b) => { const unionSize = new Set([...a, ...b]) return unionSize === a.length && unionSize === b.length }
J.Ko Sep 19 '19 at 19:49 2019-09-19 19:49
source share