This tutorial shows how to split a given array into smaller chunks. In JavaScript, we can achieve this by using while
loop and the splice()
method.
Example
const input = [1,2,3,4,5,6,7,8,9,0];
const result = [];
const chunk = 2;
if(chunk > 0){
while(input.length) {
result.push("Chunks: ",input.splice(0, chunk))
}
console.log(result);
} else {
console.log("Chunk size must be greater than 0");
}
Output
Chunks: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 0 ] ]
Now, wrapping the same code inside a function.
const input = [1,2,3,4,5,6,7,8,9,0];
const chunkSize = 3;
const chunks = function(array, size) {
if(size >= 0){
const results = [];
while (array.length) {
results.push(array.splice(0, size));
}
return results;
} else {
return "Chunk size should be greater than 0"
}
};
console.log("The split array: ",chunks(input, chunkSize));
Output
The split array: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 0 ] ]