Write a JavaScript Program to Split Array into Smaller Chunks

As a JavaScript programmer, you might often encounter situations where you need to split an array into smaller chunks.

This can be useful for a variety of reasons, such as optimizing data transmission, improving performance, or processing data in parallel.

To split an array into smaller chunks, you can use the built-in slice() method of JavaScript arrays.

This method allows you to extract a portion of an array into a new array, based on the specified start and end indices.

Here’s an example of how you can use the slice() method to split an array into chunks of a specified size:

function chunkArray(array, chunkSize) {
  const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  return chunks;

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedArray = chunkArray(myArray, 3);

console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this example, we define a function called chunkArray() that takes two parameters: the array to be chunked and the desired chunk size.

The function creates an empty array called chunks, which will hold the smaller chunks of the original array.

The function then iterates over the original array using a for loop, with a step size equal to the chunk size.

In each iteration, the function uses the slice() method to extract a portion of the original array, starting at the current index and extending to the current index plus the chunk size.

Finally, the function pushes each extracted portion into the chunks array and returns it.

To use this function, we simply pass in an array and a desired chunk size. In the example above, we create an array called myArray with values from 1 to 9, and then call the chunkArray() function with a chunk size of 3. The resulting chunkedArray variable holds the array split into chunks of 3 elements each.

In conclusion, splitting an array into smaller chunks is a common task in JavaScript programming, and can be easily accomplished using the slice() method and a simple loop.