Sometimes, we may want to divide JavaScript arrays into chunks in our code.
In this article, we’ll look at how to split a JavaScript array into chunks.
Array.prototype.slice
We can use the slice
array instance method to extract a chunk of an array with the start and end index.
The item at the start index is included, but the item at the end index isn’t.
For instance, we can write:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
let tempArray = []
const result = []
for (let i = 0, j = array.length; i < j; i += chunk) {
tempArray = array.slice(i, i + chunk);
result.push(tempArray)
}
console.log(result)
We have the array
array that we want to divide into chunks.
chunk
specifies the length of each chunk.
tempArray
has the extracted array chunk.
And we have a for loop to let us loop through array
to extract the chunks.
We increment i
by chunk
in each iteration to skip to the start of the next chunk.
Then in the loop body, we call slice
with i
and i + chunk
to return each chunk.
And we call push
with tempArray
to add it to the result
array.
Therefore, result
is:
[
[
1,
2
],
[
3,
4
],
[
5,
6
],
[
7,
8
],
[
9,
10
]
]
Array.prototype.concat and
Array.prototype.map
We can use the concat
array method to append one or more items to an array.
And we can use map
to map the values of the original array into array chunks.
For instance, we can write:
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const chunk = 2;
const result = array.map((elem, i) => {
return i % chunk ? [] : [array.slice(i, i + chunk)];
}).flat()
console.log(result)
We have the same array and chunk size as the previous example.
Then we call array.map
with a callback that checks if index i
is evenly divisible by chunk
.
If it is, then we return the array chunk with the callback with slice
.
Otherwise, we return an empty array.
We then call flat
to flatten the returned array to flatten the arrays one level to get what we want.
Since we’ve to loop through the whole array
, this is less efficient than the for loop.
Therefore, result
should be the same as what we have before.
Conclusion
We can split an array into chunks with various JavaScript array methods.