在javascript中交错多个数组 [英] interleave mutliple arrays in javascript

查看:159
本文介绍了在javascript中交错多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个数组数组,我们想将其交织到一个数组中:即:

We have an Array of arrays, which we want to interleave into a single array: i.e:

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

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

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

if arrays are not of equal length, pad it to the longest innerArray's length.

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

i.e [1, 2, 3], [4, 5]) => [1, 4, 2, 5, 3, null]

对于2个数组,我已经满足了此条件,但是如果大小写不止于此.我努力制定一项应对超过2个问题的策略.

I've satisfied this condition with the case of 2 arrays, however if the case is more than that. I struggle to form a strategy on dealing with more than 2.

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

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

推荐答案

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

You can do this for any number of arrays with two nested forEach statements:

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

这篇关于在javascript中交错多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆