vsync vsync - 1 month ago 7
Javascript Question

Split a group Array of items into N groups

I want to split a Array of numbers into N groups, which must be ordered from larger to smaller groups.

For example, in the below code, split an Array of 12 numbers into 5 Arrays, and the result should be evenly split, from large (group) to small:

[1,2,3] [4,5,6] [7,8] [9,10] [11,12]


Playground





// set up known variables
var arr = [1,2,3,4,5,6,7,8,9,10,11,12],
numberOfGroups = 5,
groups = [];

// split array into groups of arrays
for(i=0; i<arr.length; i++) {
var groupIdx = Math.floor( i/(arr.length/numberOfGroups) );

// if group array isn't defined, create it
if( !groups[groupIdx] )
groups[groupIdx] = [];
// add arr value to group
groups[groupIdx].push( arr[i] )

}

// Print result
document.write( "data: " + arr );
document.write('<br><br>')
// print groups:
while( groups.length > 0 ){
document.write( "group: " + groups.pop() );
document.write('<br>')
}





(I was googling and seeing some other answers but nothing was exactly what I wanted...)

Answer

I'm not 100% sure how this should work on different sized arrays with different group counts, but this works for your 12 digit example:

function chunkArray(arr, chunkCount) {
  const chunks = [];
  while(arr.length) {
    const chunkSize = Math.ceil(arr.length / chunkCount--);
    const chunk = arr.slice(0, chunkSize);
    chunks.push(chunk);
    arr = arr.slice(chunkSize);
  }
  return chunks;
}



var arr = [1,2,3,4,5,6,7,8,9,10,11,12];
console.log( chunkArray(arr, 5) )

Working codepen

Edit: made function easier to read/understand.