To split array into chunks with JavaScript, we use a for loop.
For instance, we write
const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
//...
}
to use a for loop to loop through i
from 0 to the array
‘s length minus 1.
We increment i
by the chunkSize
in each iteration.
In the loop, we call array.slice
with i
and i + chunkSize
to return the slice of the array
between index i
and i + chunkSize - 1
as a new array.