Last modified: Aug 03, 2026

JavaScript Chunk Array into Smaller Arrays

Working with large data sets in JavaScript can be tricky. Sometimes you need to break a big array into smaller, more manageable pieces. This process is called chunking.

Chunking is useful for pagination, batch processing, or displaying data in rows. In this guide, you will learn several simple ways to split an array into smaller arrays. We will use clean code and practical examples.

Let's start with the most straightforward method using a loop. This approach is easy to read and works in all environments.

Using a for Loop to Chunk an Array

The classic way to chunk an array is with a for loop. You iterate over the original array and slice pieces of the desired size. This method gives you full control over the process.

Here is a simple function that does the job. It takes an array and a chunk size as arguments. Then it returns a new array containing the smaller arrays.


function chunkArrayWithLoop(arr, chunkSize) {
  const result = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    // Slice a piece from the current index
    const chunk = arr.slice(i, i + chunkSize);
    result.push(chunk);
  }
  return result;
}

// Example usage
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const chunked = chunkArrayWithLoop(numbers, 3);
console.log(chunked);

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]

The loop increases the index by chunkSize each time. The slice() method extracts a portion of the array. This is efficient and easy to understand.

This method works well for most cases. However, if you prefer a more functional style, you can use reduce(). It is a powerful array method that can handle chunking elegantly.

Using reduce() to Group Elements

The reduce() method processes each item and builds a result. You can use it to create chunks by checking the last group's size. This approach is concise and modern.

Let's implement the same function using reduce(). It accumulates chunks in an accumulator array.


function chunkArrayWithReduce(arr, chunkSize) {
  return arr.reduce((result, item, index) => {
    // If the current chunk is full, start a new one
    if (index % chunkSize === 0) {
      result.push([item]);
    } else {
      // Add the item to the last chunk
      result[result.length - 1].push(item);
    }
    return result;
  }, []);
}

// Example usage
const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const chunkedLetters = chunkArrayWithReduce(letters, 2);
console.log(chunkedLetters);

[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ], [ 'g' ] ]

Notice how the modulo operator % checks if the index is a multiple of the chunk size. If yes, a new chunk starts. Otherwise, the item goes into the last chunk.

This functional approach is clean and avoids manual indexing. It is a favorite among developers who prefer declarative code. For more advanced array operations, check out this JavaScript Array reduce() guide.

Using slice() in a While Loop

Another popular technique uses a while loop with slice(). This is very similar to the first method but uses a while condition instead of a for loop. It can be more readable for some developers.

Here is how you can implement it. The loop continues until the original array is fully processed.


function chunkArrayWithWhile(arr, chunkSize) {
  const result = [];
  let i = 0;
  while (i < arr.length) {
    // Push the sliced chunk to the result
    result.push(arr.slice(i, i + chunkSize));
    i += chunkSize;
  }
  return result;
}

// Example usage
const data = [10, 20, 30, 40, 50, 60, 70];
const chunkedData = chunkArrayWithWhile(data, 4);
console.log(chunkedData);

[ [ 10, 20, 30, 40 ], [ 50, 60, 70 ] ]

The while loop is simple and performs well. It is a good alternative if you want to avoid the for loop syntax. This method also mutates no original data, which is a best practice.

Remember, all these methods return a new array. They do not change the original array. This is important for keeping your code predictable.

Handling Edge Cases

When chunking arrays, you must consider edge cases. For example, what if the chunk size is larger than the array length? Or what if the chunk size is zero?

If the chunk size is greater than or equal to the array length, the result will contain a single chunk. If the chunk size is zero or negative, you should throw an error. Let's improve our function to handle these cases.


function chunkArraySafely(arr, chunkSize) {
  if (chunkSize <= 0) {
    throw new Error('Chunk size must be a positive number');
  }
  const result = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    result.push(arr.slice(i, i + chunkSize));
  }
  return result;
}

// Test edge cases
console.log(chunkArraySafely([1, 2, 3], 5)); // One chunk
try {
  chunkArraySafely([1, 2, 3], 0);
} catch (error) {
  console.log('Error:', error.message);
}

[ [ 1, 2, 3 ] ]
Error: Chunk size must be a positive number

Adding validation makes your code more robust. It prevents unexpected behavior in your application. This is especially important when working with user input.

Also, consider what happens with an empty array. The result will be an empty array, which is correct. This is a natural outcome of the loop logic.

Chunking Array of Objects

Chunking works with any type of array, including arrays of objects. This is common when dealing with API responses or database records. The same functions work without modification.

Let's see an example with objects. We will chunk a list of users into groups of two.


const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'David' },
  { id: 5, name: 'Eve' }
];

function chunkObjects(arr, size) {
  return arr.reduce((result, item, index) => {
    const chunkIndex = Math.floor(index / size);
    if (!result[chunkIndex]) {
      result[chunkIndex] = [];
    }
    result[chunkIndex].push(item);
    return result;
  }, []);
}

console.log(chunkObjects(users, 2));

[
  [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ],
  [ { id: 3, name: 'Charlie' }, { id: 4, name: 'David' } ],
  [ { id: 5, name: 'Eve' } ]
]

This example uses Math.floor() to determine the chunk index. It is a clean way to group objects. You can then process each chunk for batch operations.

If you need to work with object keys, you might find this JavaScript Array of Objects guide helpful. It explains more about handling complex data.

Performance Considerations

For most use cases, the methods above are fast enough. However, for very large arrays, performance might matter. The slice() method creates a shallow copy, which is efficient.

The loop-based methods are generally the fastest. They have a time complexity of O(n), where n is the array length. This is optimal for this task.

If you are working with millions of items, consider using a generator function. It can yield chunks one at a time, saving memory. But for most web applications, the simple methods are sufficient.

In modern JavaScript, you can also use the new Array.from() method with a mapping function. This is a concise one-liner for chunking.


function chunkArrayWithFrom(arr, chunkSize) {
  return Array.from(
    { length: Math.ceil(arr.length / chunkSize) },
    (_, index) => arr.slice(index * chunkSize, index * chunkSize + chunkSize)
  );
}

console.log(chunkArrayWithFrom([1, 2, 3, 4, 5], 2));

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

This method is elegant and uses functional programming. It is a great addition to your toolkit. For more array techniques, see this JavaScript Array Methods guide.

Real-World Use Cases

Chunking is not just a theoretical exercise. It has many practical applications. For instance, you can use it to display data in a grid layout.

Imagine you have a list of products and want to show them in rows of three. You can chunk the array and then render each chunk as a row. This is a common pattern in e-commerce sites.

Another use case is uploading files in batches. Instead of sending all files at once, you can chunk them and upload sequentially. This reduces server load and improves reliability.

You can also use chunking for pagination in a custom component. Instead of loading all data, you can fetch and chunk it on the client side. This creates a smooth user experience.

For more ideas on manipulating arrays, check out this JavaScript Array of Arrays guide. It covers nested array operations in depth.

Conclusion

Chunking an array into smaller arrays is a fundamental skill in JavaScript. You learned several methods, including loops, reduce(), and Array.from(). Each has its strengths, so choose the one that fits your style.

Always validate your chunk size to avoid errors. Test your functions with edge cases like empty arrays or oversized chunks. This ensures your code is reliable.

Now you can confidently split arrays for any purpose. Whether you are building a UI or processing data, chunking will make your code cleaner and more efficient. Practice with your own examples to master this technique.