chunked array

Benchmark created on


Description

https://stackoverflow.com/questions/78191924/i-need-to-chunk-an-array-into-smaller-arrays-of-a-specified-size-and-im-unsure

Setup

let arr = [...new Array(25000)].map(i => Math.floor(Math.random() * 25000));

const chunk = (arr, size) => {
    const chunkedArr = [];
    let i = 0;
    while(i < arr.length) {
        chunkedArr.push(arr.splice(0, size))
    }
    return chunkedArr;
};

const chunkArray = (arr, size) => {
    // Check if the array is empty or if size is not positive
    if (arr.length === 0 || size <= 0) {
        return [];
    }

    // Calculate the number of chunks needed
    const numChunks = Math.ceil(arr.length / size);

    // Create an array to store the chunked arrays
    const chunkedArray = [];

    // Loop through the array and push chunks into the chunkedArray
    for (let i = 0; i < numChunks; i++) {
        const start = i * size;
        const end = start + size;
        chunkedArray.push(arr.slice(start, end));
    }

    return chunkedArray;
}

Teardown

arr = null;

Test runner

Ready to run.

Testing in
TestOps/sec
chunk
chunk(arr, 4000)
ready
chunkArray
chunkArray(arr, 4000)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.