← All Exercises
Deep Equality for JSON Values
intermediatejavascript
Background
Caching, undo stacks, and state diffing all need structural comparison. Comparing serialized strings is tempting, but it depends on key order and hides subtle differences such as extra properties.
Problem
Implement deepEqual(a, b) for values produced by JSON.parse. Two values are equal when primitives match with Object.is, arrays have the same length and element-wise equality, and objects have the same own keys with recursively equal values. Key insertion order must not matter.
Input
A JSON object with two properties, a and b, holding the values to compare.
Output
The literal true or false.
Sample tests
Sample 1
Input: {"a":{"x":[1,2,{"y":null}],"z":3},"b":{"z":3,"x":[1,2,{"y":null}]}}Expected: true
Sample 2
Input: {"a":{"x":[1,2]},"b":{"x":[2,1]}}Expected: false
Sample 3
Input: {"a":{"x":1},"b":{"x":1,"y":2}}Expected: false
Sample 4
Input: {"a":[{"k":1},[true,false]],"b":[{"k":1},[true,false]]}Expected: true
Sample 5
Input: {"a":{"x":1},"b":{"x":1,"y":null}}Expected: false
Your solution
Learning objective
Practice recursive structural comparison and understand the pitfalls of serialization-based equality.