I want to split an array in even (or as even as possible) chunks. The input of the function should be the array and the size of the chunks. Say you have the array
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
If you put it in the function below, with 5 as chunk size, it will result in the following
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17]
However, I want the result to be
[[1,2,3,4,5],[6,7,8,9],[10,11,12,13],[14,15,16,17]
Which means sacrificing the length of the arrays before to make them only differ one in length.
The function I'm currently using is stated below. I've tried various things with modulo but I can't figure it out.
function chunkArray(myArray, chunkSize){
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunkSize) {
myChunk = myArray.slice(index, index+chunkSize);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}