Skip to the solution
MediumDSA7 min read

Implement deepMerge(target, source) — recursive merge

711 views

The problem

Problem, as an interviewer would state it: "Implement deepMerge(target, source) — recursively merging source into target, combining NESTED objects field-by-field rather than overwriting them wholesale, and returning a genuinely NEW merged object without mutating either input."

Examples:

Code
deepMerge({a:1, b:{c:2, d:3}}, {b:{c:99}, e:5});
// {a:1, b:{c:99, d:3}, e:5}

Clarifying questions expected:

  • When BOTH target and source have a nested object at the same key, should they be recursively merged, rather than source simply overwriting target's whole object?
  • What is the real, correct behavior for an ARRAY value — should two arrays at the same key be merged together, or should source's array simply replace target's?
  • Should either input object be mutated, or must a genuinely new result be returned?

Code / implementation expected: Yes — real, direct proof of recursive nested merging, confirmation the original target is never mutated, and — critically — confirmation of the correct, real array-replacement (not array-merging) behavior.

  • deep-merge
  • object
  • recursion

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

7 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: deepMerge() correctly recursively merges nested objects while preserving untouched sibling fields, and wholesale replaces arrays rather than merging them

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 105 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

Implement curry(func) with placeholder support

Continue