Skip to the page

Frontend-flavoured problems · mid

Deep equal and JSON diff

Deep equality and JSON diff both walk two structures together: equal types, then equal keys, then recurse, and a diff records add, remove and replace operations with the path to each change, like JSON Patch.

The notes

What you must know

  • deepEqual order: same reference or Object.is → true; different types or one is null → false; arrays need equal length and order; objects need the same set of own keys (order does not matter); recurse on values.
  • Special cases to mention: NaN (Object.is), +0/−0, Dates (compare getTime), Maps/Sets, undefined-valued keys ({ a: undefined } vs {} are different), cycles (a WeakMap of compared pairs).
  • JSON.stringify comparison fails: key order matters, undefined and functions are dropped, NaN becomes null, cycles throw.
  • Diff output like JSON Patch (RFC 6902): { op: 'add' | 'remove' | 'replace', path, value }. Walk keys of a (remove/replace/recurse), then keys only in b (add).
  • Arrays: index-by-index diff is simple; a move-aware diff uses LCS (like git diff) — say the trade-off. When applying patches, remove array items from the highest index first.
  • Uses: form 'unsaved changes' detection, sending only changed fields (PATCH), undo history, React-like memo comparisons (React itself compares props shallowly with Object.is).

The red pen

Common traps: mistake → fix

  • Mistake: JSON.stringify(a) === JSON.stringify(b) is a deep equal

    Fix: key order and lost values break it.

  • Mistake: Arrays are objects, so the object branch is enough

    Fix: [1, 2] and { 0: 1, 1: 2 } must not be equal.

  • Mistake: NaN !== NaN means two NaN fields differ

    Fix: use Object.is for leaves.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement deepEqual for plain JSON values.
  2. Add NaN, Dates and cycles.
  3. Return the list of differences with paths.
  4. How would you diff arrays when items move?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview