How to chunk an array in JavaScript.

Isaac Avilez
2 min readDec 2, 2020

--

Alright, here we have yet another algorithm problem with a solution. How to chunk an array. Basically, given an array and chunk size, divide the array into many subarrays where each subarray is of length size. Sounds weird, right? Well let’s jump into it. First we always wanna start off with our function declaration, and have it with two parameters. One being the array, and the second parameter will be the size we’re chunking it to. After we do so, we want to declare a new array to hold all the chunks, and we can just simply named it chunkedArr. So far our code should be looking like so:

Function declaration.

Next thing, we want to iterate through our array. We want to use a for of helper. After that, we want to make a temporary variable within our for loop, and you can just name is last, and the purpose of that variable is to store the last element in that array. With that being done, our code should look similar to this:

Iterating through the array.

After we’ve done that, we want to have a conditional. Basically what the conditional does is it checks if the the last element does not exist, or if it’s equal to the chunk size. If it does apply, we would like to push a new chunk into our chunkedArr array with that current element we’re iterating over. Otherwise, if it doesn’t qualify, we want to simply add the current element into the current chunk. Finally, the last thing we want to do, is return our chunkedArr array. With that being done, our code should look like this:

Finished chunked algorithm.

Thanks for reading, and I hope this helps you out with understanding JavaScript, and algorithms in general!

--

--

No responses yet