0

I have two javascript arrays of same size:

let a = [1,2,3,4,5]
let b = [6,7,8,9,10]

I want to merge this in the way:

let out = [1,6,2,7,3,8,4,9,5,10] //no adjecent elements from same array

Currently, I iterate them through a loop:

let a = [1,2,3,4,5]
let b = [6,7,8,9,10]
let out = []
for(let i =0;i<a.length;i++){
    out.push(a[i])
    out.push(b[i])
}
console.log(out)

Is there a different/ better way to do the merge?

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48

2 Answers2

1

You can use .reduce() to merge the both arrays in desired format:

let a = [1, 2, 3, 4, 5];
let b = [6, 7, 8, 9, 10];

let merge = (a1, a2) => a1.reduce((r, v, i) => r.concat(v, a2[i]), []);

console.log(merge(a, b));
.as-console-wrapper { max-height: 100% !important; top: 0; }

An alternate approach could be use of .push() inside callback:

let a = [1, 2, 3, 4, 5];
let b = [6, 7, 8, 9, 10];

let merge = (a1, a2) => a1.reduce((r, v, i) => (r.push(v, a2[i]), r), []);

console.log(merge(a, b));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

The relatively new array method .flatMap() can be used here. It allows you to map values to arrays, which are then flattened into the larger resulting array. Here you can map each value from a to an array containing itself with its corresponding value in b using the index. This array will then form part of the larger resulting array:

let a = [1,2,3,4,5]
let b = [6,7,8,9,10]
let out = a.flatMap((v, i) => [v, b[i]]);
console.log(out)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64