Emmanuel Akinfulubi

JavaScriptArray

Deep compare nested arrays in JavaScript

Intermediate · 4 min read

Try [1, 2] === [1, 2] in JavaScript and you get false. Two arrays with exactly the same items, and JavaScript says they are not equal. Everyone runs into this, usually when a test fails or a "has anything changed?" check always says yes.

In this tutorial you will learn why that happens, then write two equality checks: a shallow one for flat arrays, and a deep one that also handles arrays inside arrays. You will also see where the popular JSON.stringify shortcut goes wrong. You should know arrays, arrow functions and what a function calling itself means (recursion is explained below).

Values and references

Numbers and strings are compared by value: 2 === 2 is true. Arrays are objects, and === on objects asks a different question: "are these the very same object?" It doesn't look inside.

Every time you write [1, 2], JavaScript makes a new array. So two literals are two separate objects, even if they hold the same things. A variable holds a reference to an array, like an address. Copy the variable, and you copy the address, not the array.

JavaScript

const one = [1, 2];
const alsoOne = one;
console.log([1, 2] === [1, 2]); // false: two different arrays
console.log(one === alsoOne);   // true: one array, two names

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

40 Comparing two arrays

fair

[1, 2] === [1, 2] is false. Explain that, then write an equality check that works — including for nested arrays.

Stuck? Three hints, smallest first
  1. 1. === on two arrays compares references, not contents. Two literals are two objects.
  2. 2. A shallow check compares lengths and then each element with ===.
  3. 3. For nesting, recurse when both elements are arrays.

Step 1: compare the contents

To compare what's inside, check the lengths, then check each item with ===.

Step 1

const shallowEqual = (a, b) =>
  a.length === b.length && a.every((v, i) => v === b[i]);
console.log(shallowEqual([1, 2], [1, 2])); // true
console.log(shallowEqual([1, 2], [2, 1])); // false
console.log(shallowEqual([1], [1, 2]));    // false

every is true only if its test passes for every item. The test compares item i of a with item i of b. Order matters, so [1, 2] and [2, 1] are different.

Why check the length first? Without it, [1] and [1, 2] would pass: every only walks through a, and its one item matches. The && also means every is skipped altogether when the lengths differ.

Step 2: arrays inside arrays

This is called a shallow check because it only looks one level down. Try nested arrays:

Step 2

const shallowEqual = (a, b) =>
  a.length === b.length && a.every((v, i) => v === b[i]);
console.log(shallowEqual([[1]], [[1]])); // false

Each outer array holds an inner [1], and those inner arrays are two separate objects. So v === b[i] compares two different objects and says false. We are back to the original problem, one level deeper.

Step 3: recursion

A recursive function calls itself to handle a smaller piece of the same problem. Here, "compare two items" can mean "compare two arrays", which is the job we are already writing. So when both items are arrays, call the same function on them.

Step 3

function deepEqual(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
  }
  return a === b;
}
console.log(deepEqual([[1]], [[1]]));             // true
console.log(deepEqual([1, [2, [3]]], [1, [2, [3]]])); // true
console.log(deepEqual([1, [2]], [1, [3]]));       // false
console.log(deepEqual([1, 2], [1, '2']));         // false

Array.isArray checks whether a value is an array. If both are, compare lengths and then each pair of items, using deepEqual again. If they aren't both arrays, fall back to ===. The recursion stops by itself when it reaches plain values like numbers. Any depth of nesting works.

Step 4: the JSON shortcut

You will often see this one-liner: turn both arrays into text and compare the text.

Step 4

console.log(JSON.stringify([1, [2]]) === JSON.stringify([1, [2]])); // true
console.log(JSON.stringify([undefined]));                         // [null]
console.log(JSON.stringify([null]));                              // [null]

For plain data it works. But JSON has no way to write undefined inside an array, so it writes null instead. [undefined] and [null] turn into the same text, and the shortcut calls them equal when they are not.

It has two more weak spots worth knowing. It throws an error if an array contains itself. And a Date becomes a string, so a date and the matching text look the same. Use the recursive version when any of those could be in your data.

The full solution

The panel defines shallowEqual and deepEqual, starts with the [1, 2] === [1, 2] surprise, and ends with the JSON shortcut failing on undefined. Press Run and read each line's note.

The answer

const shallowEqual = (a, b) =>
  a.length === b.length && a.every((v, i) => v === b[i]);

function deepEqual(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
  }
  return a === b;
}

const one = [1, 2];
const alsoOne = one;

console.log('[1, 2] === [1, 2] :', [1, 2] === [1, 2], '<- two different objects');
console.log('one === alsoOne   :', one === alsoOne, '<- one object, two names');
console.log('shallowEqual      :', shallowEqual([1, 2], [1, 2]));
console.log('order matters     :', shallowEqual([1, 2], [2, 1]));
console.log('--- nesting ---');
console.log('shallow on nested :', shallowEqual([[1]], [[1]]), '<- inner arrays are different objects');
console.log('deep on nested    :', deepEqual([[1]], [[1]]));
console.log('--- the JSON shortcut ---');
console.log('JSON of [undefined]:', JSON.stringify([undefined]));
console.log('JSON of [null]     :', JSON.stringify([null]), '<- identical, so JSON cannot tell them apart');

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('two arrays with equal contents are not ===', [1, 2] === [1, 2], false);
test('but an array is === itself', one === alsoOne, true);
test('a shallow check compares contents', shallowEqual([1, 2], [1, 2]), true);
test('order matters', shallowEqual([1, 2], [2, 1]), false);
test('so does length', shallowEqual([1], [1, 2]), false);
test('a shallow check fails on nesting', shallowEqual([[1]], [[1]]), false);
test('a recursive one handles it', deepEqual([[1]], [[1]]), true);
test('the JSON shortcut agrees for plain data', JSON.stringify([1, [2]]) === JSON.stringify([1, [2]]), true);
test('but it cannot tell undefined from null', JSON.stringify([undefined]) === JSON.stringify([null]), true);

Also Basic 27. The angle here is why the naive check fails: arrays are objects, and === on objects asks "the same object?", not "the same contents?". Every literal creates a new one, so [1, 2] === [1, 2] is false and always will be.

JSON.stringify(a) === JSON.stringify(b) is the one-line version, and it is what the test helper on this page uses. It is fine for plain data and wrong in three ways worth remembering: it cannot distinguish undefined from null inside an array, it throws on a cycle, and it turns a Date into a string. Write the recursive version when any of those could be in your data.

Common mistakes

  • Comparing arrays with ===. It compares references, so two separate arrays are never equal. Compare the contents.
  • Leaving out the length check. [1] and [1, 2] would then count as equal.
  • Trusting JSON.stringify for everything. It mixes up undefined and null and throws on an array that contains itself.

Try it yourself

  1. Write sameItems(a, b) that ignores order, so [1, 2] and [2, 1] are equal. (Hint: sort copies first.)
  2. Use deepEqual to compare two 3 by 3 grids of your own.
  3. Extend deepEqual so it can also compare plain objects like { a: 1 }.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.