JavaScript: Chunk an array

To chunk (split) an array into smaller arrays, use a simple reducer.

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]]

Test the code on flems.io

Explanation and more info in my Stack Overflow answer