如何将数组拆分为m和n大小的不同重复块

我有一个由40个数字组成的数组,我需要从中创建一个n和m个块长度的新数组:

const arr = [1..40];

在计算出我需要的算法之后,我得到如下结果:

[[1,2,3,4,5,6,7,8],[9,10],[11,12,13,14,15,16,17,18],[19,20],...]

我正在尝试使用此示例,但它将分成相同大小的块

function chunkArrayInGroups(arr,size) {
    var myArray = [];
    for(var i = 0; i < arr.length; i += size) {
        myArray.push(arr.slice(i,i+size));
    }
    return myArray;
}
wwwoo00mv 回答:如何将数组拆分为m和n大小的不同重复块

您可以采用动态方法来处理一组块大小。

var values = Array.from({ length: 40 },(_,i) => i + 1),chunks = [8,2],indexC = 0,indexV = 0,result = [];
    
while (indexV < values.length) {
    result.push(values.slice(indexV,indexV += chunks[indexC]));
    indexC++;
    indexC %= chunks.length;
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

,

Nina Scholzanswer非常优雅。这是一个使用生成器和迭代器的令人费解的替代方法:

function buildNestedChunksArray(maxNum,chunkDefArr) {
  var mySetValues = new Set(Object.keys(Array.from({
      length: maxNum
    }))).values(),i = 0,z = 0,result = [];
  var chunkGenerators = chunkDefArr.map(chunkSize => {
    return function*() {
      var index = 0;
      while (index < chunkSize) {
        yield mySetValues.next().value;
        index++;
      }

    }
  })
  while (i < maxNum) {
    var chunkGen = chunkGenerators[z](),chunkVals = [];
    while (next = chunkGen.next(),!next.done) {
      chunkVals.push(parseInt(next.value,10) + 1);
      i++;
    }
    z++,z %= chunkGenerators.length;
    result.push(chunkVals);
  }
  console.log(result);
}

buildNestedChunksArray(42,[6,4,2]);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

本文链接:https://www.f2er.com/3161358.html

大家都在问