将项目数组拆分为N个数组

时间:2016-10-20 23:40:30

标签: javascript arrays math

我想将一组数字拆分为 N 组,必须从较大较小组进行排序。

例如,在下面的代码中,将 12 数字的数组拆分为 5 数组,结果应均匀分割,从大(组)到小:

[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 )
&#13;
&#13;
&#13;

更新

感谢SimpleJ&#39; answer,我可以完成我的工作 用例是一种将HTML列表拆分为&#34; chunked&#34;列表,使用CSS Columns无法轻易实现的想法。

Demo page

3 个答案:

答案 0 :(得分:6)

我不是100%确定这应该如何适用于具有不同组数的不同大小的数组,但这适用于您的12位数示例:

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

答案 1 :(得分:0)

我认为这是一个数学问题,而不是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将是[[1,2,3],[4,5,6],[7,8],[9,10],[11,12]]

这适用于任意数量的团体和玩家

答案 2 :(得分:0)

@SimpleJ答案的较短版本,并且没有两次使用slice。

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