简体   繁体   English

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

[英]How to split array into different repeating chunks of m and n size

I have an array of 40 numbers and I need to create from it a new array of n and m chunks length:我有一个包含 40 个数字的数组,我需要从中创建一个新的 n 和 m 块长度数组:

const arr = [1..40];

after working out the algorithm I need, I get results like the following:在计算出我需要的算法后,我得到如下结果:

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

I'm trying to use this example but it splits onto same sizes chunks我正在尝试使用此示例,但它拆分为相同大小的块

function chunkArrayInGroups(arr, size) {
    var myArray = [];
    for(var i = 0; i < arr.length; i += size) {
        myArray.push(arr.slice(i, i+size));
    }
    return myArray;
}

You could take a dynamic approach with an array of the chunk sizes.您可以对一组块大小采取动态方法。

 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 Scholz 's answer is very elegant. Nina Scholz回答非常优雅。 Here's a somewhat convoluted alternative using generators and iterators:这是一个使用生成器和迭代器的有点复杂的替代方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM