How to chunk an array in JavaScript Solution #2

Isaac Avilez
2 min readDec 9, 2020

In my previous blog, I provided you with a solution on how to chunk an array. If you don’t recall the algorithm, or don’t know what the algorithm asks for, it’s basically given an array and chunk size, divide the array into many subarrays where each subarray is of length size. So let’s get to it. Let’s start off by writing out our function that has two parameters, one being the array, and the second parameter will be the size we’re chunking it to. We’ll start off by create yet again another variable that will be an empty array. We will name this chunkedArr. This will later store out solution to the algorithm. Our code should look like this:

Function declaration.

After that, we will write another variable, that will have a value of 0, and we will name that index. Right after that, we want to create a while loop. So we want to do it such as, while index is less than array.length, we want to slice everything from index to index + size from our original array, and we push that into our chunkedArr. After our slice statement, and we want to move onto our next index variable, and add size to it. Make sure you’re not incrementing by one here because you’ll be incrementing by the size. After our while loop, make sure to return our chunkedArr and our final code should look like so:

Algorithm solution.

This is a short but very helpful solution to this algorithm. Hopefully I helped you with understanding how to chunk an array! Thanks for reading!

--

--