Question
Let's say that I have an Javascript array looking as following:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?
Answer
The [array.slice()
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) method can
extract a slice from the beginning, middle, or end of an array for whatever
purposes you require, without changing the original array.
const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
const chunk = array.slice(i, i + chunkSize);
// do whatever
}
The last chunk
may be smaller than chunkSize
. For example when given an
array
of 12 elements the first chunk will have 10 elements, the second chunk
only has 2.
Note that a chunkSize
of 0
will cause an infinite loop.