I'm trying to split an array into chunks. The chunks should be as many as the function specifies. What I have already is
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;
};
This successfully splits the array up into the correct amount of chunks. I would like it to then make the length of each chunk as uniform as possible so if I were to split up an array like [1,2,3,4,5,6] into 4 chunks i would get [[1,2],[3,4],[5],[6]]. Any suggestions?
Another example of shortcomings: splitting up [1,2,3,4,5,6,7,8,9,10,11,12,13,14] into 8 chunks gives [[1,2,3,4,5,6,7],[8],[9],[10],[11],[12],[13],[14]]