Answer the question
In order to leave comments, you need to log in
How to compare arrays out of element order?
JS language, let's say there are two arrays:
1) [1, 2, 3, 4]
2) [2, 4, 3, 1]
how can I compare them for identity not in the order of the elements?
if through the for of, it will be through the order, but how not?
Answer the question
In order to leave comments, you need to log in
function haveSameValues(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
const count = new Map();
arr1.forEach(n => count.set(n, (count.get(n) ?? 0) + 1));
arr2.forEach(n => count.set(n, (count.get(n) ?? 0) - 1));
return [...count.values()].every(n => n === 0);
}
haveSameValues(
[ 'hello, world!!', 0, 0, 0, 1, 1, false, false ],
[ false, false, 1, 1, 0, 0, 0, 'hello, world!!' ]
) // true
haveSameValues(
[ 1, 2, 3 ],
[ 3, 2, 2 ]
) // false
haveSameValues(
[],
[]
) // true
Plan-A : sort before comparison
const areEqual = (arrA, arrB) => {
if (arrA.length !== arrB.length) return false;
const a = arrA.slice().sort(), b = arrB.slice().sort();
return a.every((el, i) => el === b[i]);
}
const areEqual = (arrA, arrB) => {
if (arrA.length !== arrB.length) return false;
const a = arrA.slice(), b = arrB.slice();
while (a.length) {
const i = b.indexOf(a.pop());
if (-1 === i) return false;
b.splice(i, 1);
}
return true;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question