如何根据给定的零件计数创建一个数组块。
例如..
var myarray = [1,2,3,4,5,6,7,8,9,10];
var bypart = 3 ;
makechunks(bypart);
预期产出为..
[1,2,3],[4,5,6],[7,8,9,10]
从大数组到3个小数组
答案 0 :(得分:1)
javascript或angular都没有内置方式。
我假设您希望所有部件的尺寸大致相同。
function splitArray(array, groups) {
var sets = [];
var groupsize = array.length / groups;
for (var i = 0, j = 0; i < groups; i++, j += groupsize) {
sets[i] = array.slice(j, j + groupsize);
}
return sets;
}
对于您的输入splitArray([1,2,3,4,5,6,7,8,9,10], 3)
,结果将为[[1,2,3],[4,5,6],[7,8,9,10]]
答案 1 :(得分:1)
您只能使用长度的一小部分并将其添加到索引中。
function chunk(array, count) {
var result = [],
size = array.length / count;
i = 0;
while (i < array.length) {
result.push(array.slice(i, i += size));
}
return result;
}
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3));
console.log(chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:-1)
你试过去谷歌吗?
以下是您的需求:
var createGroupedArray = function(arr, chunkSize) {
var groups = [], i;
for (i = 0; i < arr.length; i += chunkSize) {
groups.push(arr.slice(i, i + chunkSize));
}
return groups;
}
用法示例:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
var groupedArr = createGroupedArray(arr, 4);
var result = JSON.stringify(groupedArr);
// result: "[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14]]"
取自: http://www.frontcoded.com/splitting-javascript-array-into-chunks.html
<强>更新:强>
var makechunks = function(arr, chunksAmount) {
var chunkSize = Math.ceil(arr.length/chunksAmount);
var groups = [], i;
for (i = 0; i < arr.length; i += chunkSize) {
groups.push(arr.slice(i, i + chunkSize));
}
return groups;
}