Array equals

node v10.24.1
version: 2.0.0
endpointsharetweet
const { isArray } = Array; // Returns true if two given arrays are equal. function arrayEquals(a, b) { if (!isArray(a) || !isArray(b)) throw new Error("Both arguments must be arrays."); if (a === b) return true; if (a.length !== b.length) return false; for (var i = 0; i < a.length; i++) { const lhs = a[i]; const rhs = b[i]; if (nanEquals(lhs, rhs)) continue; if (lhs !== rhs) return false; } return true; } module.exports = arrayEquals;
const x = ["a", "b", "a"]; const y = ["b", "a", "b"]; arrayEquals(x, y);
const z = [x, y, x]; const z2 = [x, y, x]; arrayEquals(z, z2)
const z3 = [x, y, JSON.parse(JSON.stringify(x))]; arrayEquals(z, z3)
arrayEquals([1, NaN, 3], [1, NaN, 3])
arrayEquals([1, 2, 3], [1, NaN, 3])
function nanEquals(a, b) { return typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b); }
Loading…

no comments

    sign in to comment