Divide the array into pieces of N length

How to split an array (which contains 10 elements) into 4 pieces that contain a maximum of n elements.

 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 he prints:

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

The above assumes n = 3 , however the value should be dynamic.

thank

+69
javascript arrays
Jul 03 '12 at 20:27
source share
2 answers

It could be something like this:

 var arrays = [], size = 3; while (a.length > 0) arrays.push(a.splice(0, size)); console.log(arrays); 

See splice Array Method.

+169
Jul 03 2018-12-12T00:
source share

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}) 
+56
Oct. 30 '13 at 10:17
source share



All Articles