Chunking an array in JavaScript


1 min read
development
javascript

Recently I was working with some data coming out of a Redis pipeline and I wanted to take the data and split it up into an array of X items per key. I was working with PHP, this wouldn’t have been a big deal, just use array_chunk and get on with my day.

With JavaScript though, there’s no such function.

There are definitely options though. In fact, there are 46 packages out on npm at the time of this writing that appear to handle splitting / chunking an array.

While these options are completely viable, it seemed like overkill to me to introduce a new dependency just to handle something as trivial as creating an array from an array one time in my codebase.

The thing is, the concept of chunking isn’t anything complex. Start with an array and transform it into another array. Could handle it a handful of different ways, as well.

Here’s the quick and dirty that I went with to get the job done. For the sake of the blog post, the first line is generating an array with 100 numerical items:

const unchunked = Array.apply(null, { length: 100 }).map(Number.call, Number);
const unchunkedLength = unchunked.length;
const chunked = [];
const chunkSize = 3;

for (let i = 0; i < unchunkedLength; i += chunkSize) {
  chunked.push(unchunked.slice(i, i + chunkSize));
}

console.log(unchunked, chunked);

But I mean, if you would rather add an additional dependency to your codebase, by all means, don’t let me stop you ;)