Alternatingly combining array elements in JavaScript



Problem

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 −

Input

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

Output

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

Example

Following is the code −

 Live Demo

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 < max; i++){       for (let j = 0; j < arrs.length; j++){          if(arrs[j][i]){             res.push(arrs[j][i]);          }       };    };    return res; }; console.log(pickElements(arr1, arr2, arr3));

Output

[ 1, 11, 'a', 2, 12, 'b', 3, 13, 'c', 4, 14 ]
Updated on: 2021-04-22T11:45:42+05:30

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements