将数组分割成N长度的块[复制]

时间:2021-07-25 03:15:32

This question already has an answer here:

这个问题已经有了答案:

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; });