【问题标题】:interleave mutliple arrays in javascript在javascript中交错多个数组
【发布时间】:2021-05-08 05:54:00
【问题描述】:

我们有一个数组数组,我们想将它交错成一个数组: 即:

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

【问题讨论】:

    标签: javascript arrays interleave


    【解决方案1】:

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

    【讨论】:

    • 什么是下划线和双问号?
    • 下划线是第一个参数(值)的占位符,在这种情况下始终为undefined,不需要。 ?? 被称为Nullish coalescing operator,如果左边是nullundefined,它将返回右手边的值(在这种情况下是null)(如果索引不存在就是这种情况)在当前数组上)。这允许我们用null替换undefined,而不是0。
    【解决方案2】:

    您可以使用两个嵌套的 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))

    【讨论】:

    • 你是怎么想出的:idx2 * mainArr.length + idx1 成为 double forEach 中的迭代值?
    • @helloworld 由于元素是交错的,每个元素都需要根据它们在数组数组中的位置(idx2 * mainArr.length)加上它们在自己数组中的位置(+ idx1)放置跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 2012-03-14
    • 2022-11-01
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多