FrontendPro

18Implement a basic deepEqual() for nested arrays and objects

easyAbout 15 minutesCodingrecursionobjectsarrays

Problem

Implement deepEqual(a, b). It returns true when two values have the same structure and the same primitive values, however deeply nested.

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

Requirements

  • Handle primitives, arrays and plain objects, nested to any depth.
  • Arrays are equal only when they have the same items in the same order.
  • Objects are equal when they have the same own keys with deeply equal values, in any key order.
  • An array is never equal to an object, even one with the same keys.
  • NaN equals NaN.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

If a === b, they are equal (same primitive or same reference). If both are NaN, they are equal too, even though NaN === NaN is false.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever