2722. Join Two Arrays by ID
Given two arrays arr1 and arr2 of objects, merge them into a new array based on their id property. If two objects share the same id, combine their properties with arr2's values taking precedence.
📄 Problem Statement
Each object in arr1 and arr2 contains a numeric id field.
- Merge objects with the same
id. - Include properties from both objects. If a key exists in both,
arr2's value overrides. - If an
idonly appears in one array, include that object as is. - The result array should be sorted by
idin ascending order.
💡 Example
arr1 = [
{"id": 1, "x": 1},
{"id": 2, "x": 9}
]
arr2 = [
{"id": 2, "y": 10},
{"id": 3, "z": 5}
]
joinArrays(arr1, arr2)
// âžž [
// {"id": 1, "x": 1},
// {"id": 2, "x": 9, "y": 10},
// {"id": 3, "z": 5}
// ]
🧠Explanation
Use a map to store objects by their id. Loop through both arrays, and for each object:
- If
idalready exists, merge the current object into the existing one (with arr2 overriding arr1). - Else, add it to the map.
After processing, convert the map’s values to an array and sort by id.
✅ Your Solution
/**
* @param {Array} arr1
* @param {Array} arr2
* @return {Array}
*/
function joinArrays(arr1, arr2) {
const map = new Map();
for (const obj of arr1) {
map.set(obj.id, { ...obj });
}
for (const obj of arr2) {
if (map.has(obj.id)) {
map.set(obj.id, { ...map.get(obj.id), ...obj });
} else {
map.set(obj.id, { ...obj });
}
}
return Array.from(map.values()).sort((a, b) => a.id - b.id);
}