Merge two arrays with alternating Values in JavaScript


Let’s say, we are required to write a function that takes in two arrays and returns a new array that contains values in alternating order from first and second array. Here, we will just loop over both the arrays simultaneously picking values from them one after the other and feed them into the new array.

The full code for doing the same will be −

Example

const arr1 = [34, 21, 2, 56, 17];
const arr2 = [12, 86, 1, 54, 28];
let run = 0, first = 0, second = 0;
const newArr = [];
while(run < arr1.length + arr2.length){
   if(first > second){
      newArr[run] = arr2[second];
      second++;
   }else{
      newArr[run] = arr1[first];
      first++;
   }
   run++;
};
console.log(newArr);

Output

The console output for this code will be −

[
   34, 12, 21, 86, 2,
   1, 56, 54, 17, 28
]

Updated on: 19-Aug-2020

582 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements