Brian Yang
Brian Yang
algorithm designer
Mar 11, 2020 1 min read

Array Chunking

Given an array and a size, split the array items into a list of arrays of the given size.

Solution

const chunk = (array, size) => {
    const chunks = [];

    for (let item of array) {
        const lastChunk = chunks[chunks.length - 1];
        if (!lastChunk || lastChunk.length === size) chunks.push([item]);
        else lastChunk.push(item);
    }

    return chunks;
};
comments powered by Disqus