Skip to the solution
MediumDSAAsked in 20246 min read

Object Difference

789 views

The problem

Problem, as an interviewer would state it: "Implement objectDiff(a, b) — returning a description of how object b differs from object a: which paths were added, which were removed, and which changed (with the old and new value), recursing into nested objects."

Examples:

Code
objectDiff({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 }, d: 4 });
// added: { d: 4 }, removed: {}, changed: { "b.c": { from: 2, to: 3 } }

Clarifying questions expected:

  • What output shape is wanted — flat dot-paths, or a nested structure mirroring the input?
  • How should arrays be compared, and how should NaN, +0 and -0 be treated?
  • Must a key that exists with the value undefined be distinguished from a missing key?

Code / implementation expected: Yes — real, direct proof of each category, of nested paths, and of the equality edge cases.

  • object

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a deep diff reports added, removed and changed paths, with Object.is semantics for NaN and signed zero

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 102 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Array subset check

Continue