Javascript: Splitting an array into chunks (utility function)

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 method returns a shallow copy of a portion of an array into a new array object selected from to ( not included). The original array will not be modified.


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.


Software Developer at @thoughtworks | Marathon Runner | Ex-Pharmacist Writing on Coding, Technology and Running

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store