Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A variadic function to see if any number of unsorted arrays all have the same values
const areUnsortedArraysEqual = (...arrs) => {
const everyEqual = ([first, ...arr], isEqual) =>
arr.every(item => isEqual(first, item));
return (
everyEqual(arrs, (first, arr) => arr.length === first.length) &&
everyEqual(
arrs.map(arr =>
arr.reduce(
(map, item) => map.set(item, (map.get(item) || 0) + 1),
new Map()
)
),
(first, map) =>
[...new Set([...first.keys(), ...map.keys()])].every(
item => first.get(item) === map.get(item)
)
)
);
};
console.table(
Object.assign(
{},
...[
[[1, 2]], // true
[[1, 2], [1, 2]], // true
[[1, 2], [1, 2], [1, 2]], // true
[[1, 2], [2, 1]], // true
[[1, 1, 2], [1, 2, 1]], // true
[[1, 2], [1, 2, 3]], // false
[[1, 2, 3, 4], [1, 2, 3], [1, 2]], // false
[[1, 2, 2], [1, 2]], // false
[[1, 1, 2], [1, 2, 2]], // false
[[1, 2, 3], [1, 2], [1, 2, 3]] // false
].map(arrs => ({
[arrs
.map(arr => `[${arr.join(", ")}]`)
.join(", ")]: areUnsortedArraysEqual(...arrs)
}))
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.