Join Two Arrays by ID - Problem

Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two input arrays will contain an id field that has an integer value.

joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key.

If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.

If two objects share an id, their properties should be merged into a single object:

  • If a key only exists in one object, that single key-value pair should be included in the object.
  • If a key is included in both objects, the value in the object from arr2 should override the value from arr1.

Input & Output

Example 1 — Basic Merge
$ Input: arr1 = [{"id":1,"x":1},{"id":2,"x":2}], arr2 = [{"id":3,"x":3}]
Output: [{"id":1,"x":1},{"id":2,"x":2},{"id":3,"x":3}]
💡 Note: No overlapping IDs, so objects are combined and sorted by ID: 1, 2, 3
Example 2 — Property Override
$ Input: arr1 = [{"id":1,"x":1},{"id":2,"x":2}], arr2 = [{"id":1,"x":10,"y":20}]
Output: [{"id":1,"x":10,"y":20},{"id":2,"x":2}]
💡 Note: ID 1 exists in both arrays. arr2 overrides x:1 with x:10 and adds y:20
Example 3 — Complex Merge
$ Input: arr1 = [{"id":2,"a":1,"b":2},{"id":3,"a":3}], arr2 = [{"id":1,"c":4},{"id":2,"a":5}]
Output: [{"id":1,"c":4},{"id":2,"a":5,"b":2},{"id":3,"a":3}]
💡 Note: ID 2 merges: arr2's a:5 overrides arr1's a:1, but b:2 remains. Final order: 1,2,3

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 1000
  • Each object contains an id field with unique integer value within its array
  • 0 ≤ number of additional properties ≤ 10
  • Property values can be any valid JSON type

Visualization

Tap to expand
Join Two Arrays by ID{id:1,x:1}{id:2,x:2}{id:1,x:10,y:20}arr1arr2MERGE BY IDarr2 properties override arr1{id:1,x:10,y:20}{id:2,x:2}... (sorted)merged + overridefrom arr1 onlyFinal Result (sorted by ID)
Understanding the Visualization
1
Input Arrays
Two arrays of objects, each with an id field plus other properties
2
Merge Process
Combine objects by ID, arr2 properties override arr1 when conflicts arise
3
Sorted Output
Final array sorted by ID in ascending order
Key Takeaway
🎯 Key Insight: Use hash maps for O(1) ID-based merging, where arr2 values always override arr1 values in conflicts
Asked in
Google 32 Amazon 28 Facebook 25 Microsoft 22
23.4K Views
High Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen