Deep Merge of Two Objects - Problem
You're tasked with implementing a deep merge function that intelligently combines two JavaScript objects or arrays. This is a common operation in configuration management, data processing, and API response handling.
Given two values obj1 and obj2, return a deeply merged result following these rules:
- Objects: The result contains all keys from both objects. If a key exists in both, recursively deep merge their values.
- Arrays: The result has the length of the longer array. Treat indices as keys and apply the same merging logic.
- Primitives: When merging incompatible types or primitives,
obj2takes precedence.
For example, merging {a: 1, b: {x: 2}} and {b: {y: 3}, c: 4} should produce {a: 1, b: {x: 2, y: 3}, c: 4}.
Note: You can assume both inputs are valid JSON-parsed values.
Input & Output
example_1.js โ Basic Object Merge
$
Input:
obj1 = {"a": 1, "b": {"x": 2}}
obj2 = {"b": {"y": 3}, "c": 4}
โบ
Output:
{"a": 1, "b": {"x": 2, "y": 3}, "c": 4}
๐ก Note:
Object merging: 'a' comes from obj1, 'c' comes from obj2, and 'b' is deeply merged containing both 'x' and 'y'
example_2.js โ Array Merge
$
Input:
obj1 = [1, {"a": 2}]
obj2 = [{"b": 3}, 4, 5]
โบ
Output:
[{"b": 3}, 4, 5]
๐ก Note:
Array merging: Result has length 3 (longer array). Index 0: merge 1 and {"b": 3} โ {"b": 3} (obj2 wins). Index 1: merge {"a": 2} and 4 โ 4 (obj2 wins). Index 2: only obj2 has value โ 5
example_3.js โ Mixed Types
$
Input:
obj1 = {"a": [1, 2]}
obj2 = {"a": [3, 4, 5]}
โบ
Output:
{"a": [3, 4, 5]}
๐ก Note:
When merging arrays of different lengths, the result takes the longer length. Each index is merged: merge(1,3)โ3, merge(2,4)โ4, merge(undefined,5)โ5
Constraints
- Both inputs are valid JSON-parsed values
- Objects can be nested up to 1000 levels deep
- Arrays can contain up to 104 elements
- obj2 takes precedence when merging incompatible types
Visualization
Tap to expand
Understanding the Visualization
1
Compare Collections
Check if both collections are the same type (both recipe books or both ingredient lists)
2
Start with Base
Use the first collection as your starting point
3
Add New Recipes
For each recipe in the second collection, either add it (if new) or merge it (if duplicate)
4
Recursive Merging
When merging duplicate recipes, recursively merge their contents
5
Final Collection
Result contains all recipes with intelligently combined contents
Key Takeaway
๐ฏ Key Insight: Deep merging is naturally recursive - containers need their contents merged intelligently, while individual values can be directly replaced. The elegance comes from letting the recursion handle the complexity of nested structures automatically.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code