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

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

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


当前回答

打印稿版本。演示了将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);
 }
}

其他回答

ES6 Generator版本

function* chunkArray(array,size=1){
    var clone = array.slice(0);
    while (clone.length>0) 
      yield clone.splice(0,size); 
};
var a = new Array(100).fill().map((x,index)=>index);
for(const c of chunkArray(a,10)) 
    console.log(c);

嗨,试试这个——

 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)

下面的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)

下面是我使用Coffeescript列表理解的方法。可以在这里找到一篇详细介绍Coffeescript中的理解的好文章。

chunk: (arr, size) ->
    chunks = (arr.slice(index, index+size) for item, index in arr by size)
    return chunks

这是一个递归的解决方案,尾部调用优化。

const splitEvery = (n, xs, y=[]) => xs。长度= = = 0 ?y: splitEvery(n, xs.slice(n), y.concat([xs. slice(n)])片(0,n)))) console.log(splitEvery(2, [0,1,2,3,4,5,6,7,8,9]))