Explorer
Node.js

Write a function `diff(obj1, obj2)` that returns an object showing only the keys that changed and their new values.

Problem Statement

Write a function `diff(obj1, obj2)` that returns an object showing only the keys that changed and their new values.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Compare each key in both objects. šŸ’” Hint 2: If values differ, add to the diff result. šŸ’” Hint 3: For nested objects, recurse. Only include keys that actually changed. āœ… Solution: ```javascript function diff(obj1, obj2) { const result = {}; const allKeys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]); for (const key of allKeys) { if (typeof obj1[key] === "object" && typeof obj2[key] === "object" && obj1[key] !== null && obj2[key] !== null) { const nested = diff(obj1[key], obj2[key]); if (Object.keys(nested).length > 0) result[key] = nested; } else if (obj1[key] !== obj2[key]) { result[key] = obj2[key]; } } return result; } ```

Deep Object Diff

Hard
Write a function `diff(obj1, obj2)` that returns an object showing only the keys that changed and their new values.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"b":99,"c":{"d":4}}