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

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

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


当前回答

results = []
chunk_size = 10
while(array.length > 0){
   results.push(array.splice(0, chunk_size))
}

其他回答

一个很好的函数是:

function chunk(arr,times){
    if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
   var tempArray = Array() //Array to be populated with chunks
    for(i=0;i<arr.length/times;i++){
     tempArray[i] = Array() //Sub-Arrays        //Repeats for each chunk         
   for(j=0;j<times;j++){
        if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub-  Arrays with chunks
    }
     else{
       j = times //Stop loop
       i = arr.length/times //Stop loop
  }
    }
     }
   return tempArray //Return the populated and chunked array
   }

用法如下:

chunk(array,sizeOfChunks)

我对它做了注释,这样你就能理解发生了什么。

(格式有点不对,我在移动设备上编程)

results = []
chunk_size = 10
while(array.length > 0){
   results.push(array.splice(0, chunk_size))
}

下面是一个例子,我将一个数组分割成2个元素的块,只需从数组中拼接块,直到原始数组为空。 Const数组= [86,133,87,133,88,133,89,133,90,133]; Const new_array = []; Const chunksize = 2; While (array.length) { Const chunk = array.splice(0,chunksize); new_array.push(块); } console.log (new_array)

使用array .prototype.splice()并拼接它,直到数组有元素。

Array.prototype.chunk = function(size) { Let result = []; 而(this.length) { result.push(这一点。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log (arr.chunk (2));

更新

array .prototype.splice()填充原始数组,在执行chunk()之后,原始数组(arr)变成[]。

如果你想保持原始数组不变,那就复制arr数据到另一个数组,然后做同样的事情。

Array.prototype.chunk = function(size) { Let data =[…this]; Let result = []; 而(data.length) { result.push(数据。拼接(0,大小)); } 返回结果; } Const arr = [1,2,3,4,5,6,7,8,9]; console.log(分块:,arr.chunk (2)); console.log(“原始”,arr);

附注:感谢@mts-knn提到这件事。

当前排名靠前的答案存在的问题是,它们产生了不平衡的数据块。例如,当前接受的答案将把一个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]]

(摘自相关答案)