让我们说我有一个Javascript数组看起来如下:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?


当前回答

我最喜欢的是生成器generateChunks和附加函数getChunks来执行生成器。

function* generateChunks(array, size) {
    let start = 0;
    while (start < array.length) {
        yield array.slice(start, start + size);
        start += size;
    }
}

function getChunks(array, size) {
    return [...generateChunks(array, size)];
}

console.log(getChunks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9 ] ]

作为这里的补充,生成器使用进一步的getPartitions函数生成分区,以获得n个相同大小的数组。

function generatePartitions(array, count) {
    return generateChunks(array, Math.ceil(array.length / count));
}

function getPartitions(array, count) {
    return [...generatePartitions(array, count)];
}

console.log(getPartitions([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [ [ 0, 1, 2, 3 ], [ 4, 5, 6, 7 ], [ 8, 9 ] ]

与许多其他解决方案相比,生成器的一个优点是不会创建多个不必要的数组。

其他回答

ES6传播功能#ohmy #ftw

Const chunk = (size, xs) => xs.reduce ( (segments, _, index) => 索引%大小=== 0 ? […段,x。Slice (index, index + size)] 段, [] ); console.log(块(3,(1,2,3,4,5,6,7,8)));

一个有效的解决方案是通过indexChunk将解决方案与slice和push连接起来,解决方案被分割成块:

function splitChunks(sourceArray, chunkSize) { if(chunkSize <= 0) throw "chunkSize must be greater than 0"; let result = []; for (var i = 0; i < sourceArray.length; i += chunkSize) { result[i / chunkSize] = sourceArray.slice(i, i + chunkSize); } return result; } let ar1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; console.log("Split in chunks with 4 size", splitChunks(ar1, 4)); console.log("Split in chunks with 7 size", splitChunks(ar1, 7));

我推荐使用lodash。分块是其中一个有用的功能。 产品说明:

npm i --save lodash

在你的项目中包括:

import * as _ from 'lodash';

用法:

const arrayOfElements = ["Element 1","Element 2","Element 3", "Element 4", "Element 5","Element 6","Element 7","Element 8","Element 9","Element 10","Element 11","Element 12"]
const chunkedElements = _.chunk(arrayOfElements, 10)

你可以在这里找到我的样本: https://playcode.io/659171/

使用发电机

函数*块(arr, n) { 对于(设I = 0;I < arrr .length;I += n) { 加勒比海盗。Slice (i, i + n); } } let someArray = [0,1,2,3,4,5,6,7,8,9] console.log([…块(someArray, 2)]) / /[[0, 1],[2、3],[4,5],[6、7],[8 9]]

可以像这样用Typescript输入:

function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

我认为这是ES6语法的一个很好的递归解决方案:

Const chunk =函数(数组,大小){ If (!array.length) { 返回[]; } Const head = array。片(0,大小); Const tail = array.slice(size); 返回[头,…块(尾巴,大小)]; }; 块console.log(((1、2、3),2));