-2

how can I combine this:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

// and get this
let result = [1, 4, 2, 5, 3, 6];
Ryan Wilson
  • 8,662
  • 1
  • 19
  • 34
Alisa Liso
  • 36
  • 7

1 Answers1

1

use this:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

let result = [];
for (var i = 0; i < array1.length; i++) {
  result.push(array1[i]);
  result.push(array2[i]);
}
console.log(result);

or

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let result = array1.reduce(function(arr, v, i) {
  return arr.concat(v, array2[i]);
}, []);

console.log(result);
Murtaza Hussain
  • 2,592
  • 18
  • 21
Farhan
  • 847
  • 6
  • 13
  • This is great solution, thank you very much, but there is one problem. If in array2 will be less elements than array1 than last element will be 'undefined'. – Alisa Liso May 13 '19 at 19:45
  • yes.. then in that case you would need to check the length of array2 before trying to get value.. – Farhan May 13 '19 at 19:48