for...of
loop over a Set
created from the values of both arrays.Array.prototype.filter()
to compare the amount of occurrences of each distinct value in both arrays.false
if the counts do not match for any element, true
otherwise.const haveSameContents = (a, b) => {
for (const v of new Set([...a, ...b]))
if (a.filter(e => e === v).length !== b.filter(e => e === v).length)
return false;
return true;
};
haveSameContents([1, 2, 4], [2, 4, 1]); // true
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️