[Medium] LeetCode JS 30 - 2722. Join Two Arrays by ID
March 7, 2024
LeetCode 30 Days of JavaScript
This question is from LeetCode's 30 Days of JavaScript Challenge
2722. Join Two Arrays by IDQuestion Prompt
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 fromarr1
.
// Example 1:
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 two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1.
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
First, define a join
function. Within it, create a objMap
– think of it as a fast lookup table where the key is an object's id
and the value is the object itself.
Then, iterate through arr1
, putting each object into objMap
using its id
. And loop through arr2
. If an id
exists in objMap
, we use the spread operator (...
) to merge the existing object with the new values, giving priority to arr2
. If the id
is new, we add it.
With the populated objMap
, we then use Object.values()
to turn our dictionary back into an array, and return it.
var join = function (arr1, arr2) {
// 1. Dictionary for Efficiency
const objMap = {};
// 2. Populate the Dictionary
for (const obj of arr1) {
objMap[obj.id] = obj;
}
for (const obj of arr2) {
objMap[obj.id] = { ...objMap[obj.id], ...obj }; // Merge if ID exists
}
// 3. Extract Results and Sort
return Object.values(objMap);
};
For those who don’t know why we need Object.values
here. In the example above, the objMap
would be
{
1: {"id": 1, "x": 2, "y": 3},
2: {"id": 2, "x": 10, "y": 20},
3: {"id": 3, "x": 0, "y": 0}
}
The Object.values
will extract the value in each key-value pair, and then return them as an array. Thus, Object.values(objMap)
will return
[
{ id: 1, x: 2, y: 3 },
{ id: 2, x: 10, y: 20 },
{ id: 3, x: 0, y: 0 },
];