2722. Join Two Arrays by ID

Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs 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.

 

Example 1:

Example 2:

Example 3:

Constraints:

  • arr1 and arr2 are valid JSON arrays
  • Each object in arr1 and arr2 has a unique integer id key
  • 2 < = J S O N . s t r i n g i f y ( a r r 1 ) . l e n g t h < = 1 0 6 2 <= JSON.stringify(arr1).length <= 10^6 2<=JSON.stringify(arr1).length<=106
  • 2 < = J S O N . s t r i n g i f y ( a r r 2 ) . l e n g t h < = 1 0 6 2 <= JSON.stringify(arr2).length <= 10^6 2<=JSON.stringify(arr2).length<=106

From: LeetCode
Link: 2722. Join Two Arrays by ID


Solution:

Ideas:
This code first creates a Map object to store the objects in arr1 and arr2, keyed by their id. Then, it iterates through arr2 and merges each object with the existing object in the Map with the same id. If no object exists in the Map with the same id, the object is simply added to the Map. Finally, the Map is converted to an array and sorted by id. The sorted array is then returned.
Code:
/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @return {Array}
 */
var join = function(arr1, arr2) {
    const idMap = new Map();
    for (const obj of arr1) {
        idMap.set(obj.id, obj);
    }
    for (const obj of arr2) {
        const existingObj = idMap.get(obj.id);
        if (existingObj) {
            const mergedObj = {...existingObj, ...obj};
            idMap.set(obj.id, mergedObj);
        } else {
            idMap.set(obj.id, obj);
        }
    }
    const joinedArray = [...idMap.values()];
    joinedArray.sort((a, b) => a.id - b.id);
    return joinedArray;
};
07-01 06:46