Deep Equality

MediumGoogle

Prompt

Write a JavaScript function deepEqual(obj1, obj2) that checks if two given objects (or arrays) are deeply equal.

Two values are deeply equal when:

  • They are the same primitive value, compared the way Object.is compares them: NaN counts as equal to NaN, and 0 and -0 count as different.
  • They are both arrays, or both plain objects, with the same keys, and the value under each key is deeply equal.

An array is never equal to a plain object, even if they have the same keys. You only need to handle primitives, plain objects, and arrays.

Example

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