1

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

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);
      }
    }
  })
}
4

2 回答 2

2

用于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)

于 2021-02-03T23:09:54.123 回答
1

您可以使用两个嵌套的 forEach 语句对任意数量的数组执行此操作:

let arr1 = [[1,2,3],[4,5]]
let arr2 = [[1,2,3], [4,5,6], [7,8,9]]
let arr3 = [[1,2,3,4], [4,5,6], [7,8,9], [10,11,12]]

function interLeaveArrays(mainArr){
  let maxLen = Math.max(...mainArr.map(arr => arr.length))
  mainArr.forEach(arr => {
    let lenDiff = maxLen - arr.length
    for(let i=lenDiff; i>0; i--){
      arr.push(null)
    }
  })
  
  let newArr = []
  mainArr.forEach((arr, idx1) => {
    arr.forEach((el, idx2) => {
      newArr[idx2 * mainArr.length + idx1] = el
    })
  })
  return newArr
}

console.log(interLeaveArrays(arr1))
console.log(interLeaveArrays(arr2))
console.log(interLeaveArrays(arr3))

于 2021-02-03T23:16:57.400 回答