Javascript 将数组拆分为长度为 N 的块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11318680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:26:00 来源:igfitidea点击:
Split array into chunks of N length
提问by mrdaliri
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
谢谢
回答by ZER0
回答by Mirodil
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; });
console.log({arr, groups})