Splitting Array Into Chunks

Bryam Vicente
3 min readApr 19, 2021

For this blog, I’ll be going over another popular problem which is Array Chunk. Note that I’ll be using JavaScript to solve this problem!

The problem tells us that we need to create a function where it holds an array and chunk size (integer) as arguments. The goal of this function is to divide arrays into subarrays depending on the chunk size. The examples from lines 6–10 form the screen shot above do a great job in showing what the input and outputs for this function should be. Based on the first example, we have an array with a length of 4 and the chunk size is 2. The output is [[1,2], [3,4]] because the length of the subarrays have to be the same as the chunk size.

The first step in starting this problem is recognizing that we need to create a new array that would give us the subarrays. Here’s what the code should look like so far:

The next step is knowing that we need to iterate over array to check each element in the array. Remember the goal of this function is to be able to divide an array based on the chunk size (size). For this problem, I’ll be using a for of loop statement for the iteration. Inside of this for of loop, I want to create a variable that retrieves the last element inside of newArray. Here’s what the code looks like so far:

At this point, lastNumber is currently undefined because there are no elements inside of newArray yet. In order to change the value of lastNumber we need to create a conditional. If lastNumber doesn’t exist or the length of lastNumber is equal to the chunk size (size), then we should add a new chunk inside of newArray with the current number (number) being iterated inside of array. If lastNumber does exist and the length isn’t equal to size then we need to add number inside of lastNumber.

That explanation may be difficult to understand at first, but here’s what the code looks like for better visuals:

The last step for this problem is to simply return newArray after the for of loop ends. Here’s the full solution:

Here’s what the outputs should look like when using the examples from lines 28–31:

It’s always best practice to use different test cases to ensure that the solution is working properly. Please feel free to reach out or leave a comment on this blog if there are better solutions for this problem! For more info on for of statements, and Arrays, make sure to check out the resources section below!

Resources:

--

--