CodePark/ problems / Deep equal
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Recursion over nested objects

Deep equal

mediumabout 20 minutes in an interview

Implement deepEqual(a, b). It returns true when the two values have the same structure and contents, and false otherwise.

  • Primitives are compared with Object.is: NaN equals NaN, and 0 does not equal -0.
  • Arrays are equal when they have the same length and their items are deeply equal position by position.
  • Plain objects are equal when they have the same set of own keys (from Object.keys), in any order, and the values under each key are deeply equal. A key set to undefined is still a key, so { a: undefined } does not equal {}.
  • Dates are equal when they hold the same time.
  • An array never equals a plain object, and a date never equals a non-date.

Values are only primitives, arrays, plain objects and dates. There are no cycles. Don't use JSON.stringify.

Input: deepEqual({ id: 1, tags: ['a', 'b'] }, { tags: ['a', 'b'], id: 1 }) Output: truekey order doesn't matter
Input: deepEqual([1, 2, 3], [3, 2, 1]) Output: falsearray order does
Input: deepEqual({ a: undefined }, {}) Output: false