首页 > 解决方案 > 在javascript中交错多个数组

问题描述

我们有一个数组数组,我们希望将其交错成一个数组:即:

masterArray = [[1, 2, 3], ['c', 'd', 'e']] => [1, 'c', 2, 'd', 3, 'e'],

如果数组长度不相等,则将其填充到最长的 innerArray 长度。

即 [1, 2, 3], [4, 5]) => [1, 4, 2, 5, 3, null]

我已经用 2 个数组的情况满足了这个条件,但是如果情况不止于此。我很难制定处理超过 2 个的策略。

[1, 2, 3], [4, 5, 6], [7, 8, 9] => [1, 4, 7, 2, 5, 8, 3, 6, 9]

function interleave(...masterArray) {
  let rtnArray = [];
  let longestArrayPosition = getLongestArray(masterArray);
  let longestInnerArrayLength = masterArray[longestArrayPosition].length; 
  padAllArraysToSameLength(masterArray, longestInnerArrayLength); //pad uneven length arrays
  
  masterArray[0].forEach((firstArrayNum, index) => {
    const secondArrayNum = masterArray[1][index];
    rtnArray.push(firstArrayNum);
    rtnArray.push(secondArrayNum);
  });

  return rtnArray;
}

function getLongestArray(masterArray) {
  return masterArray
    .map(a=>a.length)
    .indexOf(Math.max(...masterArray.map(a=>a.length)));
}

function padAllArraysToSameLength(masterArray, maxLength) {
  return masterArray.forEach(arr => {
    if (arr != maxLength) {
      while(arr.length != maxLength) {
        arr.push(null);
      }
    }
  })
}

标签: javascriptarraysinterleave

解决方案


用于Array.from()转置数组数组(行 => 列,反之亦然),并用null. 用 展平转置的数组数组Array.flat()

const fn = arr => Array.from({ 
    length: Math.max(...arr.map(o => o.length)), // find the maximum length
  },
  (_, i) => arr.map(r => r[i] ?? null) // create a new row from all items in same column or substitute with null
).flat() // flatten the results

const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

const result = fn(arr)

console.log(result)


推荐阅读