Array comparison
suggest changeFor a simple array comparison, you can use JSON.stringify and compare the output strings:
JSON.stringify(array1) === JSON.stringify(array2)
Note that this works only if both values are JSON-serializable and do not contain cyclic references. Otherwise it may throw
TypeError: Converting circular structure to JSON.
You can use a recursive function to compare arrays.
function compareArrays(array1, array2) {
let i; let isA1; let isA2;
isA1 = Array.isArray(array1);
isA2 = Array.isArray(array2);
if (isA1 !== isA2) { // Is one an array and the other not?
return false; // Then they cannot be the same.
}
if (! (isA1 && isA2)) { // Are both not arrays?
return array1 === array2; // Compare with strict equality.
}
if (array1.length !== array2.length) { // Different lengths cannot match.
return false;
}
// iterate arrays and compare them
for (i = 0; i < array1.length; i += 1) {
if (!compareArrays(array1[i], array2[i])) { // Do items compare recursively
return false;
}
}
return true; // must be equal
}
WARNING: Using the above function is dangerous and should be wrapped in a try catch if you suspect there is a chance the array has cyclic references (a reference to an array that contains a reference to itself)
const a = [0];
a[1] = a;
const b = [0, a];
compareArrays(a, b); // throws RangeError: Maximum call stack size exceeded
Note: The function uses
===for non-array items, so{a: 0} === {a: 0}isfalse.NaNis not equal to itself either.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents