Tutorialspoint
Problem
Solution
Submissions

Deep Clone an Object

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a JavaScript function to create a deep clone of an object without using any built-in methods like JSON.parse(JSON.stringify()) or structuredClone(). The function should handle nested objects, arrays, and primitive values, creating a completely independent copy where modifications to the clone don't affect the original object.

Example 1
  • Input: obj = {a: 1, b: {c: 2, d: [3, 4]}}
  • Output: {a: 1, b: {c: 2, d: [3, 4]}} (completely independent copy)
  • Explanation:
    • The function creates a new object with the same structure.
    • Primitive value 'a: 1' is copied directly.
    • Nested object 'b' is recursively cloned.
    • Array [3, 4] inside the nested object is also cloned.
    • The result is a completely independent copy.
Example 2
  • Input: obj = {name: "John", hobbies: ["reading", "gaming"], address: {city: "NYC", zip: 10001}}
  • Output: {name: "John", hobbies: ["reading", "gaming"], address: {city: "NYC", zip: 10001}} (independent copy)
  • Explanation:
    • String primitive "John" is copied directly.
    • Array "hobbies" is recursively cloned with all its elements.
    • Nested object "address" is recursively cloned.
    • All nested properties maintain their values but are independent.
    • Modifying the clone won't affect the original object.
Constraints
  • The object can contain nested objects, arrays, and primitive values
  • You cannot use JSON.parse(JSON.stringify()) or structuredClone()
  • The clone should be completely independent of the original
  • Time Complexity: O(n) where n is the total number of properties
  • Space Complexity: O(n) for the cloned object
ArraysRecursionGoldman SachsSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursion to handle nested objects and arrays
  • Check the type of each value before cloning
  • Create new objects and arrays instead of copying references
  • Handle primitive values by direct assignment
  • Use Array.isArray() to distinguish between objects and arrays

Steps to solve by this approach:

 Step 1: Check for null and undefined values and return them as-is.
 Step 2: Handle primitive types by returning them directly.
 Step 3: Check if the value is an array using Array.isArray().
 Step 4: For arrays, create a new array and recursively clone each element.
 Step 5: For objects, create a new object and iterate through all properties.
 Step 6: Recursively clone each property value.
 Step 7: Return the completely cloned object or array.

Submitted Code :