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 −
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 ]