I have three arrays in which first index is same, so i want to merge all three array into one array based on first index element
Input:
[[1, 'A'], [2, 'B'], [3, 'C']];
[[1, 'D'], [2, 'E'], [3, 'F']];
[[1, 'G'], [2, 'H'], [3, 'I']];
Expected output
[
[ 1, 'A', 'D', 'G' ],
[ 2, 'B', 'E', 'H' ],
[ 3, 'C', 'F', 'I' ]
]
My code:
function mergeArrays(arrays) {
const mergedMap = new Map();
for (const array of arrays) {
for (const item of array) {
const key = item[0];
if (!mergedMap.has(key)) {
mergedMap.set(key, [key]);
}
mergedMap.get(key).push(...item.slice(1));
}
}
const mergedArray = Array.from(mergedMap.values());
return mergedArray;
}
const array1 = [[1, 'A'], [2, 'B'], [3, 'C']];
const array2 = [[1, 'D'], [2, 'E'], [3, 'F']];
const array3 = [[1, 'G'], [2, 'H'], [3, 'I']];
const mergedResult = mergeArrays([array1, array2, array3]);
console.log(mergedResult);
Would you please suggest any better solution?
Please note: for the simplicity i have make first index as number but in my case it is a Date object.
2
Answers
Your code seems to work fine, but there are some possible improvements you can make:
Array.prototype.reduce
method to iterate over the arrays and create the merged map, instead of using a for loop. This will make your code more concise and functional....
) to simplify the creation of the merged array from the map values, instead of using theArray.from
method.Array.prototype.concat
method to combine the items from different arrays, instead of using theArray.prototype.push
andArray.prototype.slice
methods. This will avoid mutating the original arrays and creating intermediate arrays.Here is an example of how you can rewrite your code using these suggestions:
lodash version as below