-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
  • 10,223
  • 2
  • 21
  • 40
Alisa Liso
  • 36
  • 7
  • Post the code you have tried that isn't working. – justDan May 13 '19 at 19:27
  • Please read [ask]. This question is not in an understandable state, not does it show what you have tried before asking. – E_net4 May 13 '19 at 19:28
  • Possible duplicate of [Add items to one array after each item on another array](https://stackoverflow.com/questions/51730761) – adiga May 13 '19 at 19:29

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
  • 3,851
  • 24
  • 30
Farhan
  • 887
  • 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