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 countsdeepEqual([1, 2], { 0: 1, 1: 2 });
// false — array and object are different types
deepEqual(NaN, NaN);
// true — NaN is equal to itself hereWhat it has to do
- Handle nested objects and arrays to any depth.
- Treat arrays and objects as different types.
- Treat
NaNas equal to itself.
Notes
Object.ishandlesNaN === NaNand+0 vs -0in one shot — use it for the primitive base case.- This implementation doesn't follow cyclic references. A production-grade
deepEqualwould track visited pairs in a WeakMap.
Stuck? The javascript course covers everything this challenge needs.
Try it yourself· Edit the code, then press Run
Loading playground...
- 1.compares primitives
- 2.compares nested objects to any depth
- 3.treats arrays and objects as different
- 4.treats NaN as equal to itself
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Opens MondayWorth 250 XP when it goes live.
Discussion
Sign in to postSign in to join the conversation.Sign in
No comments yet. Be the first to say something.