AniUI Academy

Deep clone a nested structure

hardArrays & ObjectsHigh freq+350 XPPractice

The spread operator copies one level. Edit copy.address.city and you have just edited the original too, which is how undo stacks and form drafts quietly corrupt state. JSON.parse(JSON.stringify(x)) is the usual escape hatch, and it throws on circular references and destroys Dates.

Implement deepClone(value) returning a copy where every nested plain object and array is a new object — nothing in the output shares a reference with the input. Primitives come through unchanged. A Date becomes a fresh Date with the same time value.

Two reference rules matter: if the same object appears at two places in the input, it must appear as one shared object at both places in the output; and a structure that refers to itself must clone without infinite recursion, with the clone referring to itself in the same way.

Arguments

valueany
A primitive, plain object, array, Date, or any nesting of those.

Returns

any — A structural copy of value with no shared references.

Examples

const source = { a: { b: [1, 2] } };
const copy = deepClone(source);
copy.a.b.push(3);
// source.a.b is still [1, 2] — the inner array was cloned
const node = { n: 1 };
node.self = node;
const copy = deepClone(node);
// copy.n === 1, copy.self === copy, copy !== node

A self-referential structure survives — the clone refers to itself the same way.

What it has to do

  • Recursively copy plain objects and arrays so nothing is shared with the input.
  • Return primitives unchanged.
  • Clone a Date into a new Date with the same time value.
  • Preserve sharing: one object appearing twice in the input appears as one object twice in the output.
  • Handle circular references without infinite recursion.
Asked atMetaMicrosoftAtlassian

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.