Vanilla JavaScript Chunk Array

β€” 2 minute read

permalink

The other day I needed to chunk an array of over a million records in batches of a maximum of 5000.

There are multiple correct ways; I will show you the one I used for chunking an array.

Chunk Array in JavaScript permalink

const input = new Array(10001);

function chunkArray(array, chunk_size) {
const results = [];

while (array.length) {
results.push(array.splice(0, chunk_size));
}

return results;
}

const result = chunkArray(input, 5000);
console.log(result.length);
// 3

So we start by defining a new array of 10001 records. Then we define our chunkArray function; it will accept an input array and a chunk_size parameter. Inside the chunkArray function, we create a new results array and while loop over the input. We then push the amount of chunk_size into our result.

Then we call the function passing it our two parameters. In this case, the result will have three arrays, two of 5000 records, and one with one record.

You can view this in action on Codepen.

See the Pen Vanilla JavaScript Chunk Array by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter