#2700
Medium JavaScript Differences between two objects
74.6% acceptance
Apr 1, 2026
146
31
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 contains 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]. 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.
Solution
TypeScript
Time O(n)
Space O(1)
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;
function objDiff(obj1: Obj, obj2: Obj): Obj {
if (Array.isArray(obj1) !== Array.isArray(obj2)) return [obj1, obj2] as any;
const result: Obj = {};
for (const key of Object.keys(obj1)) {
if (!(key in (obj2 as any))) continue;
const v1 = (obj1 as any)[key];
const v2 = (obj2 as any)[key];
if (
typeof v1 === "object" &&
v1 !== null &&
typeof v2 === "object" &&
v2 !== null
) {
const diff = objDiff(v1, v2);
if (Object.keys(diff).length > 0) {
(result as any)[key] = diff;
}
} else if (v1 !== v2) {
(result as any)[key] = [v1, v2];
}
}
return result;
}