Coding Challenge - #28: Deep Clone Object

Write a function deepClone(obj) that returns a deep copy of a given nested object or array containing primitive values. For example, modifying a nested property in the clone returned by deepClone({ a: 1, b: { c: 2 } }) must not modify the original object.

function deepClone(obj) {
  // Your code here
}

Rules:

  • Must handle nested objects and arrays of arbitrary depth.
  • Must properly preserve primitive data types (numbers, strings, booleans, null).
  • Do not use structuredClone() or JSON.parse(JSON.stringify()).

Post your solution as a reply. Answer goes up in about a day.

I always think about this like building a physical model. You have to make sure each piece is a new one, not just pointing to the old one. If you use the same brick, changing it changes the original wall. For code, I guess it’s like iterating through each part and making a new copy. I’m not sure how to handle all the different types though. :thinking:

function deepClone(obj) {

if (obj === null || typeof obj !== “object”) {

return obj;

}

if (Array.isArray(obj)) {

return obj.map(deepClone);

}

const clone = {};

for (const key in obj) {

if (Object.hasOwn(obj, key)) {

  clone\[key\] = deepClone(obj\[key\]);

}

}

return clone;

}

yo @emmawalter5, love seeing the thought process here! the answer drops later today, so we’ll see how it stacks up.

Challenge solution: The challenge requires a deep cloning function for objects and arrays containing primitive values, without using built-in structuredClone or JSON serialization.

One way to do it:

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  let clone;
  if (Array.isArray(obj)) {
    clone = [];
    for (let i = 0; i < obj.length; i++) {
      clone[i] = deepClone(obj[i]);
    }
  } else {
    clone = {};
    for (let key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        clone[key] = deepClone(obj[key]);
      }
    }
  }
  return clone;
}

Why:
This solution uses recursion to traverse the input object or array. It handles primitive values by returning them directly. For objects and arrays, it creates a new instance and then recursively calls deepClone for each of its properties or elements, ensuring that all nested structures are also copied independently.


Got it: @emmawalter5 :trophy:

First-answer leaderboard

  1. @emmawalter5 - 9 (firsts) :trophy:
  2. @kirupa - 8 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

Hmm, the solution from @sarah_connor is quite similar to @emmawalter5’s. Both use recursion and handle primitives and arrays correctly. I wonder if either of them considered circular references. That’s usually the next step in these challenges.