Javascript: Splitting an array into chunks (utility function)

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.


var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];console.log(animals.slice(2));
// expected…