Skip to main content
08

Implement deepEqual

Mediumrecursionobjectsarrays

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Implement deepEqual(a, b). It returns true when the two values have the same structure and contents, even if they are different objects in memory, and false otherwise.

=== compares objects by reference, so two objects with the same contents are never equal with it. Tests, React's memoization and state libraries all need a structural comparison instead.

js
deepEqual({ a: 1, b: [1, 2] }, { a: 1, b: [1, 2] }) // true
deepEqual({ a: 1 }, { a: 1, b: 2 }) // false
deepEqual([1, 2, 3], [1, 2, 3]) // true
deepEqual([1, 2], { 0: 1, 1: 2 }) // false
deepEqual(NaN, NaN) // true

Requirements

  • Primitives are equal when === says so, with one exception: NaN equals NaN.
  • Arrays are equal when they have the same length and their items are deeply equal, in order.
  • Plain objects are equal when they have the same own keys (in any order) and the values under each key are deeply equal.
  • An array never equals a plain object, and null only equals null.
  • { a: undefined } and { b: undefined } are not equal: they have different keys.

Note

You don't need to handle Date, Map, Set, class instances or circular references. Inputs are made of primitives, plain objects and arrays.

Approach

Check the cheap cases first, then recurse:

  1. Same value: if a === b, return true. This covers equal primitives and the same object passed twice.
  2. NaN: NaN !== NaN, so check Number.isNaN(a) && Number.isNaN(b) explicitly.
  3. Not both objects: if either is not an object, or is null (typeof null is 'object'), the values differ.
  4. Array vs. object: if one is an array and the other isn't, return false.
  5. Keys: compare Object.keys(a).length with Object.keys(b).length, then check every key of a exists in b (with Object.hasOwn) and that the values are deeply equal.

Arrays need no special loop: Object.keys of an array is its indices, so step 5 compares them item by item, and the length check catches arrays of different sizes.

The undefined trap

Comparing only a[key] with b[key] treats { a: undefined } and { b: undefined } as equal, because b.a is also undefined. Checking Object.hasOwn(b, key) catches the missing key.

Complexity

O(n) time, where n is the total number of values in both structures, since each one is visited once. The recursion depth is the nesting depth of the input.

Follow-ups interviewers ask

  • Circular references: keep a Map of pairs already being compared, and treat a pair seen again as equal, or the recursion never ends.
  • More types: compare Dates with getTime(), RegExps with source and flags, and Maps and Sets by their entries.
  • Prototypes: should an instance of a class equal a plain object with the same fields? Comparing Object.getPrototypeOf makes the answer no.
  • Shallow equal: the one-level version React uses for memo and PureComponent props.

Reference solution

js
/**
 * @param {*} a
 * @param {*} b
 * @returns {boolean}
 */
export default function deepEqual(a, b) {
  if (a === b) return true
  if (Number.isNaN(a) && Number.isNaN(b)) return true
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
  if (Array.isArray(a) !== Array.isArray(b)) return false

  const keysA = Object.keys(a)
  const keysB = Object.keys(b)
  if (keysA.length !== keysB.length) return false

  return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]))
}
ts
export default function deepEqual(a: unknown, b: unknown): boolean {
  if (a === b) return true
  if (Number.isNaN(a) && Number.isNaN(b)) return true
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
  if (Array.isArray(a) !== Array.isArray(b)) return false

  const objectA = a as Record<string, unknown>
  const objectB = b as Record<string, unknown>
  const keysA = Object.keys(objectA)
  const keysB = Object.keys(objectB)
  if (keysA.length !== keysB.length) return false

  return keysA.every((key) => Object.hasOwn(objectB, key) && deepEqual(objectA[key], objectB[key]))
}