【发布时间】:2014-07-01 09:53:56
【问题描述】:
我正在尝试将数组拆分为块。块应该与函数指定的一样多。我已经拥有的是
groupBySize = function(array, groupSize){
if(groupSize === 0){
return;
}
var groups = [];
var i,j,temparray;
for (i=0,j=array.length; i<j; i+=groupSize) {
temparray = array.slice(i,i+groupSize);
groups.push(temparray);
}
return groups;
};
groupByNumberOfGroups = function(array, NumberOfGroups){
var groupSize = Math.floor(array.length/NumberOfGroups);
var groups = this.groupBySize(array, groupSize);
// Let's make sure we get the right amount of groups
while(groups.length > NumberOfGroups){
console.log(groups.length + ">" + NumberOfGroups);
var last = groups[(groups.length-1)];
for(var j = 0; j< last.length; j++){
var temp = j;
while(groups[temp].length > groups[temp+1]){
temp++;
}
groups[j].push(last[j]);
}
groups.pop();
}
return groups;
};
这成功地将数组拆分为正确数量的块。我希望它使每个块的长度尽可能统一,所以如果我将像 [1,2,3,4,5,6] 这样的数组拆分为 4 个块,我会得到 [[1,2 ],[3,4],[5],[6]]。 有什么建议吗?
另一个缺点示例:将 [1,2,3,4,5,6,7,8,9,10,11,12,13,14] 分成 8 个块,得到 [[1,2,3 ,4,5,6,7],[8],[9],[10],[11],[12],[13],[14]]
【问题讨论】:
-
我不这么认为,这里已经使用了这个答案的想法,OP 询问如何获得适当大小的块
标签: javascript arrays distribution content-length