Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Split a JavaScript Array into Chunks

1 min read .
Split a JavaScript Array into Chunks

JavaScript does not have a built-in chunk method for splitting an array into equally sized groups, but the operation is easy to implement with slice.

Chunking is useful for UI grids, pagination helpers, batching API operations, and processing large collections in smaller units.

A Simple chunk Function

function chunk(array, size) {
    if (!Number.isInteger(size) || size <= 0) {
        throw new RangeError('size must be a positive integer');
    }

    const result = [];

    for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
    }

    return result;
}

Use it like this:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(chunk(numbers, 3));

Output:

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

If the array length is not divisible by the chunk size, the final group is smaller:

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

A reduce Version

You can also write the helper with reduce:

function chunk(array, size) {
    if (!Number.isInteger(size) || size <= 0) {
        throw new RangeError('size must be a positive integer');
    }

    return array.reduce((result, _, index) => {
        if (index % size === 0) {
            result.push(array.slice(index, index + size));
        }
        return result;
    }, []);
}

The loop version is usually easier to scan because the control flow directly expresses the chunk boundaries.

Avoid Extending Array.prototype

It is technically possible to add a custom method to Array.prototype, but application code should usually avoid doing so. Prototype modifications can conflict with libraries, future language additions, and assumptions made by other code.

A standalone function is explicit, portable, easy to test, and does not change global behavior.

Non-Mutating Behavior

This implementation does not modify the original array because slice returns new arrays:

const original = [1, 2, 3, 4];
const groups = chunk(original, 2);

console.log(original); // [1, 2, 3, 4]
console.log(groups);   // [[1, 2], [3, 4]]

The elements themselves are not deeply cloned, so object references inside the chunks still refer to the same objects as the original array.

Conclusion

A small chunk helper is enough to split arrays into predictable groups. Validate the chunk size, prefer a standalone function over modifying built-in prototypes, and remember that slice copies the array structure rather than deeply cloning nested values.

Related Posts

chevron-up