AniUI Academy
hard+350 XPPractice

Diff two objects into added, removed and updated

Sending the entire object on every save loses concurrent edits made by someone else and makes the audit log useless. Sending only what changed needs a diff.

Implement diffObjects(before, after). Compare only the top-level own keys of the two objects and return an object with exactly three keys: added, removed and updated, each a plain object, each empty when nothing falls into it. added maps each key present in after but not in before to its new value. removed maps each key present in before but not in after to its old value. updated maps each key present in both whose values differ to an object { from, to } holding the old and new values. Values are compared structurally to any depth: nested objects and arrays with the same contents count as unchanged, an array is never equal to a plain object, and NaN counts as equal to itself. A nested change is reported as one entry for the whole top-level key, with from and to being the whole old and new values. Neither input is modified.

What it has to do

  • Return exactly the keys added, removed and updated, each a plain object.
  • Compare only top-level own keys, but compare their values structurally to any depth.
  • Report each changed key as { from, to } under updated.
  • Leave unchanged keys out of the result entirely.
  • Treat NaN as equal to itself, and never treat an array as equal to a plain object.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.