Vanilla JavaScript Chunk Array


How to chunk an array in pieces

28 May, 2020 · 2 min read

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

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);
// 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!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter