0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Chunk Array into Smaller Arrays

Use a function like 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

Input[1, 2, 3, 4, 5], size = 2
Output[[1, 2], [3, 4], [5]]
Input["a", "b", "c", "d"], size = 3
Output[["a", "b", "c"], ["d"]]
Input[], size = 4
Output[]
🧠

How to Think About It

To chunk an array, think about taking slices of the original array starting from the beginning, each slice having the specified size. Move forward by that size each time until you reach the end. Collect these slices into a new array to return.
📐

Algorithm

1
Get the input array and chunk size.
2
Create an empty array to hold chunks.
3
Start from the first element, take a slice of the array from current index to current index plus chunk size.
4
Add this slice to the chunks array.
5
Move the current index forward by chunk size.
6
Repeat until the entire array is processed, then return the chunks array.
💻

Code

javascript
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));
Output
[[1,2],[3,4],[5]]
🔍

Dry Run

Let's trace chunkArray([1, 2, 3, 4, 5], 2) through the code

1

Initialize result array

result = []

2

First iteration (i=0)

slice arr[0:2] = [1, 2], result = [[1, 2]]

3

Second iteration (i=2)

slice arr[2:4] = [3, 4], result = [[1, 2], [3, 4]]

4

Third iteration (i=4)

slice arr[4:6] = [5], result = [[1, 2], [3, 4], [5]]

5

End loop and return

return [[1, 2], [3, 4], [5]]

iSlice takenResult 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

Using while loop
javascript
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));
This uses a while loop instead of for loop but works similarly; choice depends on preference.
Using reduce
javascript
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));
This uses reduce to build chunks dynamically; more functional style but slightly more complex.

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.

ApproachTimeSpaceBest For
For loopO(n)O(n)Simple and clear chunking
While loopO(n)O(n)Similar to for loop, preference-based
Reduce methodO(n)O(n)Functional style, more expressive
💡
Always check if the chunk size is positive and handle empty arrays to avoid errors.
⚠️
Forgetting to increment the index by the chunk size causes an infinite loop or incorrect chunks.