Partition an Array in Javascript

At times it’s necessary to partition an array in to equal size chunks. This is a simple JS one-liner that makes it really easy to do.

 

Array(Math.ceil(a.length / size)).fill(0).map((_,i) => a.slice(i * size, (i+1) * size));

 

Example Usage:

 

const a = [1,2,3,4,5,6,7,8,9];

function partition(a,size){
    return Array(Math.ceil(a.length / size)).fill(0).map((_,i) => a.slice(i * size, (i+1) * size));
}

Array(9).fill(0).map((_,i) => console.log(partition(a,i+1)));

/*
[ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ] ]
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
[ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9 ] ]
[ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9 ] ]
[ [ 1, 2, 3, 4, 5, 6 ], [ 7, 8, 9 ] ]
[ [ 1, 2, 3, 4, 5, 6, 7 ], [ 8, 9 ] ]
[ [ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 9 ] ]
[ [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ]

*/

Leave a Reply

Your email address will not be published. Required fields are marked *