Wednesday, June 5, 2024
126
rated 0 times [  130] [ 4]  / answers: 1 / hits: 17758  / 7 Years ago, wed, november 1, 2017, 12:00:00

I would like to merge 2 arrays with a different length:


let array1 = ["a", "b", "c", "d"];
let array2 = [1, 2];

The outcome I would expect is ["a", 1 ,"b", 2, "c", "d"]


What's the best way to do that?


More From » ecmascript-6

 Answers
48

You could iterate the min length of both array and build alternate elements and at the end push the rest.





var array1 = [a, b, c, d],
array2 = [1, 2],
result = [],
i, l = Math.min(array1.length, array2.length);

for (i = 0; i < l; i++) {
result.push(array1[i], array2[i]);
}
result.push(...array1.slice(l), ...array2.slice(l));

console.log(result);





Solution for an arbitrary count of arrays with a transposing algorithm and later flattening.





var array1 = [a, b, c, d],
array2 = [1, 2],
result = [array1, array2]
.reduce((r, a) => (a.forEach((a, i) => (r[i] = r[i] || []).push(a)), r), [])
.reduce((a, b) => a.concat(b));

console.log(result);




[#56044] Monday, October 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
armandoh

Total Points: 208
Total Questions: 94
Total Answers: 112

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;