#Objects#Recursion

Deep Equality

Compare two values structurally, because === only ever compares references.

By Pratik RaiMedium

Write deepEqual(a, b) returning whether the two values are structurally equal.

Two objects are equal when they have the same keys and every corresponding value is deeply equal; key order does not matter. Two arrays are equal when they have the same length and equal values in the same order. Primitives compare with ===, except that NaN equals NaN.

Examples

Input:

JSfile.javascript
1deepEqual({ x: [1, 2] }, { x: [1, 2] });

Output:

true

Different objects, identical structure.

Constraints

  • Values contain only objects, arrays, numbers, strings, booleans and null

Notes

  • An array is never equal to an object, even one with matching numeric keys.
  • typeof null is "object", so it needs its own guard.

Goal: Return true only when the two values match all the way down.

Sources

Frequently asked questions

Why doesn't === work for comparing objects?
Because it compares references, not contents. Two objects are `===` only when they are the same object, so `{a:1} === {a:1}` is false even though they look identical.
How do you compare two objects by value?
Recursively: same key count, then every key present in both with deeply equal values. Arrays additionally need the same length and matching order.
What edge cases catch people out?
`typeof null` is `"object"`, so `null` needs its own guard. An array and an object can share identical keys, so `Array.isArray` must match on both sides. And `NaN === NaN` is false, so equal `NaN`s need deciding explicitly.
Is there a built-in for this?
Not in the language. `Object.is` fixes `NaN` and `-0` but is still a shallow comparison. Test frameworks and utility libraries ship their own, and `JSON.stringify` comparison only works when key order happens to match.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Deep Clone

Copy a nested structure so nothing is shared — including the cases that break a naive recursion.

JavaScript · ES6Pratik Rai ·

JavaScript

Make Object Immutable

Freeze an object all the way down, because Object.freeze only handles the top level.

JavaScript · ES6Pratik Rai ·

JavaScript

Array.prototype.groupBy

Group an array into buckets by a key function — now a real language feature as Object.groupBy.

JavaScript · ES6Pratik Rai ·