
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.
- The function creates a new object with the same structure.
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.
- String primitive "John" is copied directly.
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
Editorial
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. |
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