How to Split Array into Chunks
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:
for...of
You can loop through the array using the for…of loop breaking it smaller chunks like this:
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 splice() array method to extract elements of the specified size from the array that is received:
As the splice() element directly changes the received array, you should use the spread operator (…) 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 push() method.