call(back)
FrontendmediumSign in to star problems

Implement deepEqual

Write deepEqual(a, b) returning whether two values are structurally equal. Values are primitives, arrays, or plain objects, nested to any depth, with no cycles.

  • Primitives compare by value; NaN equals NaN, and 0 equals -0.
  • Arrays are equal when they have the same length and pairwise-equal elements; an array never equals an object.
  • Objects are equal when they have the same own keys and equal values for each key. A key present with the value undefined is still a key.
deepEqual({ a: [1, { b: null }] }, { a: [1, { b: null }] })  // true
deepEqual([1, 2], [2, 1])                                    // false
deepEqual({ a: 1 }, { a: 1, b: undefined })                  // false

Hints

Hint 1

Handle the leaf cases first: strict equality or both NaN, then type and null checks that rule out mismatched shapes.

Hint 2

For arrays compare lengths then recurse by index; for objects compare key counts, then check every key of one exists in the other and recurse.

Asked at