JSON Deep Equal - Problem

Given two values o1 and o2, return a boolean value indicating whether the two values are deeply equal.

For two values to be deeply equal, the following conditions must be met:

  • If both values are primitive types (string, number, boolean, null), they are deeply equal if they pass the === equality check
  • If both values are arrays, they are deeply equal if they have the same elements in the same order, and each element is also deeply equal according to these conditions
  • If both values are objects, they are deeply equal if they have the same keys, and the associated values for each key are also deeply equal according to these conditions

Note: You may assume both values are the output of JSON.parse. In other words, they are valid JSON.

Constraint: Please solve it without using lodash's _.isEqual() function.

Input & Output

Example 1 — Basic Object Comparison
$ Input: o1 = {"name": "John", "age": 25}, o2 = {"name": "John", "age": 25}
Output: true
💡 Note: Both objects have same keys ("name", "age") with identical values ("John", 25), so they are deeply equal
Example 2 — Array with Different Elements
$ Input: o1 = [1, 2, 3], o2 = [1, 2, 4]
Output: false
💡 Note: Arrays have same length but different elements at index 2: 3 ≠ 4, so not deeply equal
Example 3 — Nested Structure Match
$ Input: o1 = {"user": {"id": 1, "pets": ["cat"]}}, o2 = {"user": {"id": 1, "pets": ["cat"]}}
Output: true
💡 Note: Both have same nested structure: user.id = 1 and user.pets = ["cat"] in both objects

Constraints

  • Both values are valid JSON (output of JSON.parse)
  • Objects can have nested properties of any depth
  • Arrays can contain mixed types (numbers, strings, objects, arrays)
  • Cannot use lodash's _.isEqual() function

Visualization

Tap to expand
JSON Deep Equal: Complete Structure ComparisonObject 1Object 2{ "name": "John", "age": 25, "pets": ["cat"]}{ "name": "John", "age": 25, "pets": ["cat"]}Recursive Check:✓ Same keys✓ Same values✓ Same nested arraysResult: true
Understanding the Visualization
1
Input
Two JSON objects with nested structures
2
Process
Recursively compare types, keys, values, and array elements
3
Output
Boolean indicating if structures are deeply equal
Key Takeaway
🎯 Key Insight: Recursion naturally handles nested structures by breaking down complex comparisons into simpler type-specific checks
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen