W3docs

How to Split Array into Chunks

Read the tutorial and find several easy and fast approaches to splitting a JavaScript array into smaller chunks. Choose one of the methods and try examples.

This article is aimed at providing different methods of splitting an array into smaller chunks.

slice()

You can use a for loop to iterate through the array while repeatedly slicing chunks of the specified size using the slice() method. You can increase the iterator by the specified size on each iteration so as to start each new group after the previous one ended:

Javascript slice chunk method

javascript— editable

for...of

You can loop through the array using the for…of loop breaking it smaller chunks like this:

Javascript for..of chunk method

javascript— editable

The if statement is used within the for...of loop for checking whether the result array is currently empty or the last chunk is complete. If it is complete, you can create a new group with the current value and push it into the result array. If it isn't complete, you can get the last array from the result and push the current value into it until the group is complete, in other words if the required size is reached.

splice()

You can use the <kbd class="highlighted">splice()</kbd> array method to extract elements of the specified size from the array that is received:

Javascript splice chunk array method

javascript— editable

As the <kbd class="highlighted">splice()</kbd> element directly changes the received array, you should use the spread operator <kbd class="highlighted">(…)</kbd> to create a copy so that the operations do not affect the data that is received. Then each group created is added to the result by invoking the <kbd class="highlighted">push()</kbd> method.