compare-arrays-ignoring-order
Version:
This is a very simple library containing a function that allows you to compare arrays ignoring their order. This means that if two arrays have some elements mixed up, the function will return true.
43 lines (42 loc) • 1.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = isEqualArraysIgnoreOrder;
function isEqualArraysIgnoreOrder(a, b) {
if (a === b) {
return true;
}
if (typeof a !== typeof b) {
return false;
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
for (let elem of a) {
let found = false;
for (let other of b) {
if (isEqualArraysIgnoreOrder(elem, other)) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
if (typeof a === "object" && typeof b === "object") {
let keys1 = Object.keys(a);
let keys2 = Object.keys(b);
if (!isEqualArraysIgnoreOrder(keys1.sort(), keys2.sort())) {
return false;
}
for (let key of keys1) {
if (!isEqualArraysIgnoreOrder(a[key], b[key])) {
return false;
}
}
return true;
}
return false;
}