Split Array of items into N Arrays

arrays, javascript, math

Solution

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) )

Problem

I want to split an 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: ``` source: [1,2,3,4,5,6,7,8,9,10,11,12] ⬇ output: [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 console.log( "data: ", arr ); console.log( "groups: ", groups ) ``` Update: Thanks to SimpleJ's answer, I could finish my work. The use case for this is an algorithm which splits HTML lists into "chunked" lists, a think which cannot be easily achieved by using CSS Columns. Demo page

Original source