I have three arrays that share the same first index, and I am looking to combine them into one array based on the 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' ]
]
Here is my code for achieving this:
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);
Do you have any suggestions for improving this solution?
Please note: in my actual scenario, the first index is a Date object rather than a number for simplicity.