将数组拆分为 N 个长度的块

如何将数组(包含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);

然后打印出来:

['a', 'b', 'c']
['d', 'e', 'f']
['j', 'h', 'i']
['j']

上面假设 n = 3,但是,值应该是动态的。

谢谢

126449 次浏览

It could be something like that:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];


var arrays = [], size = 3;
    

while (a.length > 0)
arrays.push(a.splice(0, size));


console.log(arrays);

See splice Array's method.

An alternative method that does not mutate the array, beside create a shallow copy of it before chunk it, could be done by using slice and a for…loop:

var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];


var arrays = [], size = 3;
    

for (let i = 0; i < a.length; i += size)
arrays.push(a.slice(i, i + size));


console.log(arrays);

While a more functional programming oriented approach, could be:

const chunks = (a, size) =>
Array.from(
new Array(Math.ceil(a.length / size)),
(_, i) => a.slice(i * size, i * size + size)
);


let a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];


console.log(chunks(a, 3));
console.log(chunks(a, 2));

See Array.from and how new Array(n) works, specifically.

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