Alternatingly combining array elements in JavaScript

We are required to write a JavaScript function that takes in any number of arrays of literals as input.

Our function should prepare a new array that contains elements picked alternatingly from all the input arrays.

For example, if the input to the function is ?

Problem

Input

const arr1 = [1, 2, 3, 4];
const arr2 = [11, 12, 13, 14];
const arr3 = ['a', 'b', 'c'];

Expected Output

const output = [1, 11, 'a', 2, 12, 'b', 3, 13, 'c', 4, 14];

The function should take the first element from each array, then the second element from each array, and so on until all elements are combined.

Solution

Following is the code ?

const arr1 = [1, 2, 3, 4];
const arr2 = [11, 12, 13, 14];
const arr3 = ['a', 'b', 'c'];

const pickElements = (...arrs) => {
    const res = [];
    const max = Math.max(...arrs.map(el => el.length));
    
    for(let i = 0; i 

Output

[ 1, 11, 'a', 2, 12, 'b', 3, 13, 'c', 4, 14 ]

How It Works

The function uses the rest parameter (...arrs) to accept any number of arrays. It finds the maximum length among all arrays using Math.max() and map().

The outer loop iterates through each index position (0, 1, 2, etc.), while the inner loop goes through each array at that position. We check for undefined instead of using truthy check to handle falsy values like 0 or empty strings properly.

Example with Different Array Lengths

const short = [1, 2];
const medium = ['x', 'y', 'z', 'w'];
const long = [100, 200, 300];

console.log(pickElements(short, medium, long));
[ 1, 'x', 100, 2, 'y', 200, 'z', 300, 'w' ]

Conclusion

This solution efficiently combines elements from multiple arrays in alternating order. The key is using nested loops and checking for undefined to handle arrays of different lengths correctly.

Updated on: 2026-03-15T23:19:00+05:30

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements