Code Snippets
/

Chunk an Array into Fixed Sizes

Chunk an Array into Fixed Sizes

Splitting an array into fixed-size groups is a recurring need for pagination, batch API calls, and grid layouts. This snippet covers a one-line slice loop, a generator variant for streaming large inputs, and the edge cases (size <= 0, non-integer size, non-multiple lengths) that bite production code. Drop it in as a tiny utility and stop reaching for lodash for one helper.

JavaScript
Easy
3 snippets
arrays
utility
code-template
array-manipulation-patterns

544 views

17

function chunk(array, size) {
    const result = [];
    for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
    }
    return result;
}

console.log(chunk([1, 2, 3, 4, 5], 2));
// [[1, 2], [3, 4], [5]]

The simplest correct implementation walks the source in steps of size and pushes a slice(i, i + size) for each window. slice clamps to array.length, so the final group is whatever is left, which is why [1, 2, 3, 4, 5] chunked by 2 yields a trailing [5]. This runs in O(n) time and O(n) extra space because every element is copied exactly once into a new array. Reach for this version when the input fits comfortably in memory and you just need a clean pagination helper.