Differences Between Two Objects - Problem

Write a function that accepts two deeply nested objects or arrays obj1 and obj2 and returns a new object representing their differences.

The function should compare the properties of the two objects and identify any changes. The returned object should only contain keys where the value is different from obj1 to obj2. For each changed key, the value should be represented as an array [obj1 value, obj2 value].

Important: Keys that exist in one object but not in the other should not be included in the returned object. The end result should be a deeply nested object where each leaf value is a difference array.

When comparing two arrays, the indices of the arrays are considered to be their keys. You may assume that both objects are the output of JSON.parse.

Input & Output

Example 1 — Basic Object Differences
$ Input: obj1 = {"a": 5, "b": 1}, obj2 = {"a": 1, "b": 1}
Output: {"a": [5, 1]}
💡 Note: Key 'a' has different values (5 vs 1), key 'b' has same values (1 vs 1) so not included
Example 2 — Nested Object Changes
$ Input: obj1 = {"a": {"b": 2}}, obj2 = {"a": {"b": 3}}
Output: {"a": {"b": [2, 3]}}
💡 Note: Nested property a.b differs: 2 vs 3, so result maintains nested structure
Example 3 — Array Index Comparison
$ Input: obj1 = [1, 2, 3], obj2 = [1, 3, 3]
Output: {"1": [2, 3]}
💡 Note: Array index 1 differs (2 vs 3), indices 0 and 2 are same so not included

Constraints

  • Objects are valid JSON structures
  • Nested depth ≤ 100 levels
  • Total properties ≤ 104

Visualization

Tap to expand
Object Differences: Find What ChangedOriginal ObjectModified ObjectDifferences Found{ a: 5, b: 1}{ a: 1, b: 1}{ a: [5, 1]}compareextractOnly properties with different values are includedProperty 'b' has same value (1) in both objects → not includedProperty 'a' differs (5 vs 1) → included as [5, 1]
Understanding the Visualization
1
Input Objects
Two nested objects or arrays to compare
2
Deep Comparison
Recursively compare each common property
3
Difference Object
Result containing only changed values as [old, new] arrays
Key Takeaway
🎯 Key Insight: Only compare common keys and represent differences as [old_value, new_value] arrays
Asked in
Facebook 35 Google 28 Netflix 22
23.0K Views
Medium Frequency
~25 min Avg. Time
890 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