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

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

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


当前回答

我推荐使用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/

其他回答

下面的ES2015方法不需要定义函数,直接在匿名数组上工作(例如块大小为2):

[11,22,33,44,55].map((_, i, all) => all.slice(2*i, 2*i+2)).filter(x=>x.length)

如果你想为此定义一个函数,你可以这样做(改进K._对Blazemonger的回答的评论):

const array_chunks = (array, chunk_size) => array
    .map((_, i, all) => all.slice(i*chunk_size, (i+1)*chunk_size))
    .filter(x => x.length)

打印稿版本。演示了将101个随机uid分成10个组

const idArrayLengthLimit = 10;
const randomOneHundredOneIdArray = Array
    .from(Array(101).keys())
    .map(() => generateUid(5));

function generateUid(length: number) {
  const uidString: string[] = [];
  const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    uidString
      .push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
  }
  return uidString.join('');
}

for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
 if(i % idArrayLengthLimit === 0){
     const result = randomOneHundredOneIdArray
       .filter((_,id) => id >= i && id < i + idArrayLengthLimit);
    // Observe result
    console.log(result);
 }
}

我最喜欢的是生成器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 ] ]

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

当前排名靠前的答案存在的问题是,它们产生了不平衡的数据块。例如,当前接受的答案将把一个101个元素的数组分布为10个大小为10的块,后面是一个大小为1的块。

使用一些模块化算法可以创建统一的块大小,差异永远不会超过1:

函数split_array(a, nparts) { const quot = Math.floor;长度/ nparts) Const rem = a.length % nparts Var部件= [] For (var I = 0;I < nparts;+ + i) { const begin = i * quot +数学。分钟(rem,我) Const end = begin + quot + (i < rem) parts.push (a。片(开始、结束) } 返回部分 } Var chunk = split_array([1,2,3,4,5,6,7,8,9,10], 3) console.log (JSON.stringify(块)

输出:

[[1,2,3,4],[5,6,7],[8,9,10]]

(摘自相关答案)

嗨,试试这个——

 function split(arr, howMany) {
        var newArr = []; start = 0; end = howMany;
        for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
            newArr.push(arr.slice(start, end));
            start = start + howMany;
            end = end + howMany
        }
        console.log(newArr)
    }
    split([1,2,3,4,55,6,7,8,8,9],3)