Last active
November 21, 2023 08:39
-
-
Save vyspiansky/7f089f1fc8a76d65d53f1c73b387c8a7 to your computer and use it in GitHub Desktop.
JavaScript: interleave many arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function is quite flexible because it can handle any number of input arrays and | |
// doesn't require them to be of equal length. It interleaves as many elements as possible | |
// from each array, in the order that the arrays (and elements) were provided. | |
/** | |
* Interleaves elements of multiple arrays. | |
* The function takes any number of arrays as arguments. | |
*/ | |
function interleaveArrays(...args) { | |
// Find the maximum length among all arrays | |
const max = Math.max(...args.map(arr => arr.length)); | |
const result = []; | |
for (let i = 0; i < max; i++) { | |
for (let arr of args) { | |
if (i < arr.length) { | |
result.push(arr[i]); | |
} | |
} | |
} | |
return result; | |
} | |
const array1 = [1, 2, 3]; | |
const array2 = ['A', 'B', 'C', 'D', 'E']; | |
const array3 = ['i', 'ii']; | |
const array4 = ['a', 'b', 'c']; | |
const result = interleaveArrays(array1, array2, array3, array4); | |
console.log(result); | |
// Output: [1, "A", "i", "a", 2, "B", "ii", "b", 3, "C", "c", "D", "E"] | |
// Try https://jsfiddle.net/vyspiansky/6wtxpb9g/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment