我想将数字数组分成N组,必须从larger to smaller groups.
例如,在下面的代码中,分割一个数组12数入5数组,结果应该从大(组)到小均匀分割:
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]
操场 http://jsbin.com/fotuyuw/edit?js,output
// 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:
感谢 SimpleJ 的answer https://stackoverflow.com/questions/40166199/split-a-group-array-of-items-into-n-groups#answer-40166342,我可以完成我的工作了。
其用例是一种将 HTML 列表拆分为“分块”列表的算法,这是通过使用无法轻松实现的想法CSS 列 https://developer.mozilla.org/en-US/docs/Web/CSS/columns.
演示页面 http://codepen.io/vsync/pen/ORrJgz?editors=0010