Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
62 views
in Technique[技术] by (71.8m points)

javascript - Efficient way to mix arrays

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If arrays are mostly the same length, find max length and iterate over the arrays:

let
  arrays = [
    [1, 2, 3],
    ['a', 'b'],
    [100, 101, 102, 103]
  ];
let maxLength = 0;
let result = [];
for (let i = 0; i < arrays.length; i++) {
  let len = arrays[i].length;
  if (len) {
    maxLength < len && (maxLength = len);
    result.push(arrays[i][0]);
  }
}
for (let i = 1; i < maxLength; i++) {
  for (let j = 0; j < arrays.length; j++) {
    if (i < arrays[j].length) {
      result.push(arrays[j][i]);
    }
  }
}

console.log(...result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...