逐列遍历数组数组(子数组)

Looping through array of arrays (subarray), column by column

这是我的子数组数组

const array = [
[0, 1, 2, 3],             // Loop from top to bottom?
[4, 5, 6, 7, 8, 9],       // |
[10, 11, 12, 13, 14],     // |
[15, 16, 17, 18, 19],     // |
]                         // V

我正在尝试获取此输出

newArray = [0, 4, 10, 15, 1, 5, 11, 16, 2, 6, 12 ...] 

这是我目前的想法

      let idx = 0;
      let newArray = []
      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array[i].length; j++) {
          newArray.push(array[idx][j])
          idx++;
        }
        idx = 0;
      }

这是一个可能的解决方案:

const array = [
  [0, 1, 2, 3],             // Loop from top to bottom?
  [4, 5, 6, 7, 8, 9],       // |
  [10, 11, 12, 13, 14],     // |
  [15, 16, 17, 18, 19],     // |
]
// if there is "more" to read
let hasMore = true;
// result
const res = [];
// "column" index
let el = 0;
while(hasMore){
  // let's assume there is nothing more to read
  hasMore = false;
  // go through all the elements in the input array
  for(let i = 0; i < array.length; i++){ 
    // if the el-th element exists
    if(array[i][el] != undefined){
      // there there might be something more to read
      // with "something more" I mean that exists the el+1 th column
      hasMore = true;
      // add the element
      res.push(array[i][el])
    }
  }
  // move to the next column
  el++;
}
console.log(res);

函数式风格的可能解决方案可能是:

const array = [
  [0, 1, 2, 3],             // Loop from top to bottom?
  [4, 5, 6, 7, 8, 9],       // |
  [10, 11, 12, 13, 14],     // |
  [15, 16, 17, 18, 19],     // |
]
const res = array.flatMap(
  el => el.map(
    (o, i) => ({
      index: i,
      el: o
    })
  ))
  .sort((a, b) => a.index - b.index)
  .map(({el}) => el)

console.log(res)

不确定这是否是解决方案,因为这会创建一个新数组,但可能会有所帮助。 var newArray = Array.prototype.concat.apply([], array);

这是使用以下方法的组合执行此操作的另一个示例:

const array = [
  [0, 1, 2, 3],
  [4, 5, 6, 7, 8, 9],
  [10, 11, 12, 13, 14],
  [15, 16, 17, 18, 19],
]

var final = Object.values(
  array.reduce((acc, cur) => (
    cur.map((elm, idx) => idx in acc ? acc[idx].push(elm) : acc[idx] = [elm]), acc
  ), {})
).flat();

const pre = document.createElement('pre');
pre.innerText = JSON.stringify(final);
document.querySelector('body').appendChild(pre);