Suppose you have:
const xs = [1,2,3];
const ys = [3,2,1];
This seems to work:
xs.every(x => ys.includes(x));
//=> true
But it gives you false positives:
const xs = [2,2,2];
const ys = [1,2,3];
xs.every(x => ys.includes(x));
//=> true
// But…
ys.every(y => xs.includes(y));
//=> false
Another example:
const xs = [2];
const ys = [1,2,3];
xs.every(x => ys.includes(x));
//=> true
// But…
ys.every(y => xs.includes(y));
//=> false
We could compare the size of both arrays and bail out quickly but technically these two arrays do contain the same elements:
const xs = [2];
const ys = [2,2,2];
ys.every(y => xs.includes(y));
//=> true
xs.every(x => ys.includes(x));
//=> true
The way I would answer this question is by computing the set of unique values for both arrays.
const similar = (xs, ys) => {
const xsu = [...new Set(xs).values()]; // unique values of xs
const ysu = [...new Set(ys).values()]; // unique values of ys
return xsu.length != ysu.length ? false : xsu.every(x => ysu.includes(x));
}
similar([1,2,3],[3,2,1]);
//=> true
similar([2,2,2],[3,2,1]);
//=> false
similar([2],[3,2,1]);
//=> false
similar([2],[2,2,2]);
//=> true
similar([1,2,3],[4,5,6]);
//=> false