This question already has an answer here:
这个问题已经有了答案:
- How to split a long array into smaller arrays, with JavaScript 14 answers
- 如何用JavaScript 14的答案将一个长数组分割成更小的数组
How to split an array (which has 10 items) into 4 chunks, which contain a maximum of n
items.
如何将一个数组(有10个条目)分割成4个块,最多包含n个条目。
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
//a function splits it to four arrays.
console.log(b, c, d, e);
And it prints:
和它打印:
['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']
The above assumes n = 3
, however, the value should be dynamic.
上面假设n = 3,但是值应该是动态的。
Thanks
谢谢
2 个解决方案
#1
156
It could be something like that:
可以是这样的:
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
See splice Array's method.
看到拼接数组的方法。
#2
45
Maybe this code helps:
也许这段代码可以帮助:
var chunk_size = 10;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
var groups = arr.map( function(e,i){
return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null;
})
.filter(function(e){ return e; });
#1
156
It could be something like that:
可以是这样的:
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
See splice Array's method.
看到拼接数组的方法。
#2
45
Maybe this code helps:
也许这段代码可以帮助:
var chunk_size = 10;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
var groups = arr.map( function(e,i){
return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null;
})
.filter(function(e){ return e; });