将项目数组拆分为N个数组 [英] Split Array of items into N Arrays
问题描述
我想将一组数字拆分为 N 组,必须从较大到较小组进行排序。
I want to split a Array of numbers into N groups, which must be ordered from larger to smaller groups.
例如,在下面的代码中,将 12 数字的数组拆分为 5 数组,结果应该平均分割,从大(组)到小:
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 )
感谢SimpleJ的回答,我可以完成我的工作。
这个用例是一种将HTML列表分成分块列表的算法,这个想法通过使用无法轻易实现 CSS专栏。
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.
推荐答案
我不是100%确定这应该如何适用于具有不同组数的不同大小的数组,但这适用于您的12位数示例:
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) )
这篇关于将项目数组拆分为N个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!