Given two arrays arr1 and arr2, return a new array joinedArray. Each object in the input arrays contains an id field. joinedArray will merge arr1 and arr2 based on the id. The length of joinedArray should be the length of unique id values. The returned array should be sorted in ascending order by id.
If an id exists in one array but not in the other, the object should be included in the merged array. If two objects share an id, their properties should be merged as follows:
arr2 should overwrite the value from arr1.// Example 1
Input:
arr1 = [
{"id": 1, "x": 1},
{"id": 2, "x": 9}
],
arr2 = [
{"id": 3, "x": 5}
]
Output:
[
{"id": 1, "x": 1},
{"id": 2, "x": 9},
{"id": 3, "x": 5}
]
Explanation: There are no common ids, so arr1 and arr2 are merged directly.
// Example 2
Input:
arr1 = [
{"id": 1, "x": 2, "y": 3},
{"id": 2, "x": 3, "y": 6}
],
arr2 = [
{"id": 2, "x": 10, "y": 20},
{"id": 3, "x": 0, "y": 0}
]
Output:
[
{"id": 1, "x": 2, "y": 3},
{"id": 2, "x": 10, "y": 20},
{"id": 3, "x": 0, "y": 0}
]
Explanation: The common id is 2, so the id 2 from arr2 overrides the id 2 from arr1.
const arr1 = [
{"id": 1, "x": 2, "y": 3},
{"id": 2, "x": 3, "y": 6}
]
const arr2 = [
{"id": 2, "x": 10, "y": 20},
{"id": 3, "x": 0, "y": 0}
]
function joinTwoArraysByID(arr1, arr2){
const twoArrayMap = new Map()
const resultArray = []
arr1.forEach(item => {
twoArrayMap.set(item.id, item)
})
arr2.forEach(item => {
twoArrayMap.set(item.id, item)
})
for (var [key, value] of twoArrayMap) {
console.log(key + " : " + value)
resultArray.push(value)
}
return resultArray
}
joinTwoArraysByID(arr1, arr2)
function joinTwoArraysByID(arr1, arr2) {
const objMap = {};
for (const obj of arr1) {
objMap[obj.id] = obj;
}
for (const obj of arr2) {
objMap[obj.id] = { ...objMap[obj.id], ...obj };
}
return Object.values(objMap);
}