AniUI Academy

Compare two objects properly

mediumArrays & ObjectsHigh freq+250 XPOpens Monday

=== on two objects compares references, not contents — so {a:1} === {a:1} is false. For state diffing, test assertions, or React memo keys you want structural equality instead.

Implement deepEqual(a, b) returning true when the two values have the same shape and the same leaf values. Recurse into nested objects and arrays, and handle the awkward edges NaN, null, and the array-vs-object distinction correctly.

Arguments

aunknown
The first value to compare.
bunknown
The second value to compare.

Returns

boolean — true if the two inputs are structurally equal, otherwise false.

Examples

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

deepEqual({ a: 1 }, { a: 1, b: 2 });
// false — different key counts
deepEqual([1, 2], { 0: 1, 1: 2 });
// false — array and object are different types

deepEqual(NaN, NaN);
// true — NaN is equal to itself here

What it has to do

  • Handle nested objects and arrays to any depth.
  • Treat arrays and objects as different types.
  • Treat NaN as equal to itself.

Notes

  • Object.is handles NaN === NaN and +0 vs -0 in one shot — use it for the primitive base case.
  • This implementation doesn't follow cyclic references. A production-grade deepEqual would track visited pairs in a WeakMap.
Asked atMetaGoogleAmazon

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
Opens MondayWorth 250 XP when it goes live.

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.