one day of code

Segment a one-dimensional array to groups of N

January 04, 2021

const breakArray = (arr, chunkCount) =>
Array.from(
{
length: Math.ceil(arr.length / chunkCount),
},
(_, index) => arr.slice(index * chunkCount, index * chunkCount + chunkCount)
)

Example:

breakArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c'], 5)
/*
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0],
['a', 'b', 'c']
]
*/

Written by Milan Miljkovic — a tech enthusiast and design system practitioner.