In this LeetCode coding problem, we are given two arrays arr1
and arr2
, for which we have to 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 both the arraysarr1
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
Solution: Using Frequency Counter approach
/**
* @param {Array} arr1
* @param {Array} arr2
* @return {Array}
*/
const join = function(arr1, arr2) {
const ob = {};
for(const i of arr1) {
ob[i.id] = i;
}
for(const i of arr2) {
ob[i.id] = ob[i.id] ? {...ob[i.id], ...i} : i;
}
return Object.values(ob);
};
Test Cases:
Example 1: There are no duplicate ids so arr1
is simply concatenated with arr2
.
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}
]
Example 2: The two objects with common id are merged together. The keys from arr2
override the values in arr1
. Rest of the array gets concatenated normally.
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}
]
Example 3:
Input:
arr1 = [{"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}]
arr2 = [ {"id": 1, "b": {"c": 84}, "v": [1, 3]}]
Output: [
{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}
]
Performance: