Merge two arrays with alternating Values in JavaScript

Merging two arrays with alternating values means creating a new array that picks elements from each array in turn: first element from array1, first element from array2, second element from array1, and so on.

Using While Loop with Index Tracking

This approach uses separate counters to track positions in each array and alternates between them:

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);
[
  34, 12, 21, 86,  2,
   1, 56, 54, 17, 28
]

Using For Loop (Simpler Approach)

A more straightforward method that alternates based on index parity:

const arr1 = [10, 30, 50];
const arr2 = [20, 40, 60];
const merged = [];
const maxLength = Math.max(arr1.length, arr2.length);

for(let i = 0; i < maxLength; i++){
    if(i < arr1.length) merged.push(arr1[i]);
    if(i < arr2.length) merged.push(arr2[i]);
}

console.log(merged);
[ 10, 20, 30, 40, 50, 60 ]

Using Array Methods

A functional approach using reduce() for more concise code:

const arr1 = ['a', 'c', 'e'];
const arr2 = ['b', 'd', 'f'];

const alternating = arr1.reduce((result, item, index) => {
    result.push(item);
    if(arr2[index] !== undefined) {
        result.push(arr2[index]);
    }
    return result;
}, []);

console.log(alternating);
[ 'a', 'b', 'c', 'd', 'e', 'f' ]

Handling Different Array Lengths

When arrays have different lengths, remaining elements from the longer array are appended:

const short = [1, 2];
const long = [10, 20, 30, 40, 50];
const result = [];
const maxLength = Math.max(short.length, long.length);

for(let i = 0; i < maxLength; i++){
    if(i < short.length) result.push(short[i]);
    if(i < long.length) result.push(long[i]);
}

console.log(result);
[ 1, 10, 2, 20, 30, 40, 50 ]

Comparison

Method Readability Performance Handles Different Lengths
While Loop Medium Good Yes
For Loop High Good Yes
Array Methods High Slightly slower Requires extra handling

Conclusion

The for loop approach offers the best balance of readability and performance. Use array methods for functional programming style, but consider performance for large datasets.

Updated on: 2026-03-15T23:18:59+05:30

935 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements