EN
JavaScript - split array into chunks
0 points
In this article, we would like to show you how to split array into chunks using JavaScript.
Quick solution:
xxxxxxxxxx
1
const array = [1, 2, 3, 4, 5, 6, 7];
2
3
const chunkSize = 3;
4
5
for (let i = 0; i < array.length; i += chunkSize) {
6
const chunk = array.slice(i, i + chunkSize);
7
console.log(chunk);
8
}
In this example, we create a reusable arrow function that splits the array
into chunks with given chunkSize
.
xxxxxxxxxx
1
const splitArray = (array, chunkSize) => {
2
for (let i = 0; i < array.length; i += chunkSize) {
3
const chunk = array.slice(i, i + chunkSize);
4
5
// Do something with chunks e.g:
6
console.log(chunk);
7
}
8
}
9
10
11
// Usage example:
12
13
const array = [1, 2, 3, 4, 5, 6, 7]
14
15
splitArray(array, 3);
Note:
The last chunk's size may be different than chunkSize. Its size is equal to the number of the remaining elements.