A simple reducer to chunk (split) an array into smaller arrays.
For example, with a chunk size of 3:
// Before
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// After
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
Here's how:
const chunk = (array, size) =>
array.reduce((acc, _, i) => {
if (i % size === 0) acc.push(array.slice(i, i + size))
return acc
}, [])
// Usage:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunked = chunk(numbers, 3)
console.log(chunked) //=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
At every nth iteration (where n = size
; starting at the first iteration),
the accumulator array (acc
)
is appended with a chunk of the array (array.slice(i, i + size)
)
and then returned.
At other iterations,
the accumulator array is returned as-is.
If size
is zero,
the method returns an empty array.
If size
is negative,
the method returns broken results.
So, if needed in your case,
you may want to do something about negative or non-positive size
values.