Javascript: Splitting an array into chunks (utility function)

Sherlynn
2 min readJan 23, 2019

For a work project, I needed to include a wizard form with 2 questions on each page. To get the total page count, I divided the total number of questions by 2 and then rounded it off to the nearest integer. There were however some problems with that implementation and a more efficient solution was required.

My tech lead pointed out the usage of Array chunking. So this is how it works:

In the above, we define a function named Chunk which takes in 2 parameters: an original array and the chunk size.

Then, we define a temporary array called tempArray and let it be an empty array.

Subsequently, we use the Array.slice() method in a for loop. The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Example:

var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

For each chunk, we then push it into our tempArray (initially an empty array) to get a new Array of our desired outcome.

Now, we can count each item in the array as individual pages for our Wizard form. This is definitely a more elegant way to implement paging logic for multi-step Wizard forms.

Cheers!

Sherlynn