JavaScript Program to Chunk Array into Smaller Arrays
function chunkArray(arr, size) { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; } to split an array into smaller arrays of given size.Examples
How to Think About It
Algorithm
Code
function chunkArray(arr, size) { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; } console.log(chunkArray([1, 2, 3, 4, 5], 2));
Dry Run
Let's trace chunkArray([1, 2, 3, 4, 5], 2) through the code
Initialize result array
result = []
First iteration (i=0)
slice arr[0:2] = [1, 2], result = [[1, 2]]
Second iteration (i=2)
slice arr[2:4] = [3, 4], result = [[1, 2], [3, 4]]
Third iteration (i=4)
slice arr[4:6] = [5], result = [[1, 2], [3, 4], [5]]
End loop and return
return [[1, 2], [3, 4], [5]]
| i | Slice taken | Result array |
|---|---|---|
| 0 | [1, 2] | [[1, 2]] |
| 2 | [3, 4] | [[1, 2], [3, 4]] |
| 4 | [5] | [[1, 2], [3, 4], [5]] |
Why This Works
Step 1: Loop through array in steps
The for loop moves through the array by increments of the chunk size, ensuring each chunk is the correct length.
Step 2: Use slice to get chunks
The slice method extracts a part of the array from the current index to the index plus chunk size without modifying the original array.
Step 3: Collect chunks in result
Each sliced chunk is added to the result array, which is returned after the loop finishes.
Alternative Approaches
function chunkArray(arr, size) { const result = []; let i = 0; while (i < arr.length) { result.push(arr.slice(i, i + size)); i += size; } return result; } console.log(chunkArray([1, 2, 3, 4, 5], 2));
function chunkArray(arr, size) { return arr.reduce((chunks, item) => { const last = chunks[chunks.length - 1]; if (!last || last.length === size) { chunks.push([item]); } else { last.push(item); } return chunks; }, []); } console.log(chunkArray([1, 2, 3, 4, 5], 2));
Complexity: O(n) time, O(n) space
Time Complexity
The function loops through the entire array once, slicing chunks, so time grows linearly with input size.
Space Complexity
A new array is created to hold the chunks, so space also grows linearly with input size.
Which Approach is Fastest?
The for loop and while loop approaches have similar performance; reduce is more expressive but slightly slower due to function calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop | O(n) | O(n) | Simple and clear chunking |
| While loop | O(n) | O(n) | Similar to for loop, preference-based |
| Reduce method | O(n) | O(n) | Functional style, more expressive |