Split Array of items into N Arrays

2020-07-26 03:59发布

问题:

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

回答1:

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



回答2:

I think this is a more of a mathematical problem than a Javascript.

const getGroups = (arr, noOfGroups) => {
  const division = Math.floor(arr.length / numberOfGroups);
  const groups = [[]];
  let remainder = arr.length % numberOfGroups;
  let arrIndex = 0;
  for (let i = 0; i < noOfGroups; i++) {
    for (let j = division + (!!remainder * 1); j >= 0; j--) {
      groups[i].push(arr[arrIndex]);
      arrIndex += 1;
    }
    remainder -= 1;
  }

  return groups;
};

const myGroups = getGroups([1,2,3,4,5,6,7,8,9,10,11,12], 5);

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

This will work for any number of groups and players



回答3:

A shorter version of @SimpleJ answer and without using slice two times.

function splitArrayEvenly(array, n) {
  array = array.slice();
  let result = [];
  while (array.length) {
    result.push(array.splice(0, Math.ceil(array.length / n--)));
  }
  return result;
}

console.log(splitArrayEvenly([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 5))