Given a number of different sized Arrays:
let allArrays = [ [1, 2, 3], [a, b], [100, 101, 102, 103] ]
I want to take the first element from each array, then the second element from each array, and so on:
let finalArray = [ 1, a, 100, 2, b, 101, 3, 102, 103 ]
My current, na?ve solution is to simply loop through allArrays
until allArrays.flat()
is empty, building a new array on the way:
let arr = [ [1, 2, 3], ['a', 'b'], [100, 101, 102, 103] ]
const new_arr = []
while (arr.flat().length) {
for (let sub_arr of arr) {
if (sub_arr.length) {
new_arr.push(sub_arr.shift())
}
}
}
new_arr
// [ 1, 'a', 100, 2, 'b', 101, 3, 102, 103 ]
This strikes me a quite inefficient. What would be the best way to go about this?
Edit to clarify what I'm looking for: Some of the arrays can sometimes be thousands of elements long, and the code is run in the frontend, so I'm searching for a method that is fast.
Also, the lengths and combinations of lengths vary considerably, so rather than optimizing for a single scenario, I'm looking for a way that will be guaranteed to be reasonably fast no matter how the arrays look.
question from:
https://stackoverflow.com/questions/65830888/efficient-way-to-mix-arrays