Comparing Arrays Deeply
You'll learn how to correctly compare two arrays element-by-element, including nested arrays, using a recursive approach.
Why Length Comes First
Before diving into element comparison, always check if both arrays have the same length. If they don't, they can't possibly be equal—no need to waste time comparing elements. This simple guard clause makes your function more efficient.
function deepArrayEqual(arr1, arr2) {
// Guard: different lengths = not equal
if (arr1.length !== arr2.length) {
return false;
}
// Now compare each element at the same index
for (let i = 0; i < arr1.length; i++) {
const item1 = arr1[i];
const item2 = arr2[i];
// If both are arrays, recurse
if (Array.isArray(item1) && Array.isArray(item2)) {
if (!deepArrayEqual(item1, item2)) {
return false;
}
}
// Otherwise compare directly
else if (item1 !== item2) {
return false;
}
}
return true;
}
How It Works
Think of it like checking two identical shopping lists: first verify they have the same number of items, then go line-by-line comparing each entry. If you find a nested list within an item (like "3 apples: red, green, yellow"), you recursively check that sub-list too.
The recursion handles arrays nested to any depth:
deepArrayEqual([1, [2, 3]], [1, [2, 3]]); // true
deepArrayEqual([1, [2, 4]], [1, [2, 3]]); // false
deepArrayEqual([1, 2], [1, 2, 3]); // false (length check)
Key Takeaway: When comparing arrays deeply, check length equality first for efficiency, then recursively compare each element at the same index, drilling down into nested arrays as needed.