Split Array into Chunks

Split array into chunks

When working with JavaScript, you may come across situations where you need to split an array into smaller chunks. This can be useful for various reasons, such as processing data in batches or displaying data in a paginated manner. In this blog post, we will explore multiple solutions to split an array into chunks using JavaScript.

Solution 1: Using a for loop

One way to split an array into chunks is by using a for loop. Here’s an example code snippet:

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 array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;
const result = chunkArray(array, chunkSize);
console.log(result);

This code defines a chunkArray function that takes an array and a chunk size as parameters. It initializes an empty array called chunks to store the resulting chunks. The for loop iterates over the original array, slicing it into chunks of the specified size using the slice method. Each chunk is then pushed into the chunks array. Finally, the function returns the array of chunks.

The output of the above code will be:

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

Solution 2: Using the reduce method

Another approach to split an array into chunks is by using the reduce method. Here's how you can do it:

function chunkArray(array, chunkSize) {
  return array.reduce((chunks, element, index) => {
    if (index % chunkSize === 0) {
      chunks.push([element]);
    } else {
      chunks[chunks.length - 1].push(element);
    }
    return chunks;
  }, []);
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;
const result = chunkArray(array, chunkSize);
console.log(result);

In this code, the chunkArray function uses the reduce method to iterate over the original array. It checks if the current index is divisible by the chunk size to determine when to start a new chunk. If it is, a new array is pushed into the chunks array. Otherwise, the element is added to the last chunk in the array. The function returns the array of chunks.

The output of the above code will be the same as in the previous solution:

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

These are two common solutions to split an array into chunks using JavaScript. Depending on your specific use case, you can choose the approach that best suits your needs. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *