Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I divide an array into equal-sized chunks in JavaScript?

You can see the code I wrote below

I tried to create function it does no work as expected

function chunkArray(array, chunkSize) {
  const chunks = [];
  let index = 0;

  while (index < array.length) {
    chunks.push(array.slice(index, index + chunkSize));
    index += chunkSize;
  }

  return chunks;
}

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArray(myArray, 3);
console.log(chunkedArray); // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the chunkArray function provided below to divide an array into equal-sized chunks. The function takes an array and the desired chunk size as parameters, and it returns an array of arrays where each subarray represents a chunk.

The function iterates over the input array using a while loop and uses the slice method to extract the current chunk from the array. The starting index of each chunk is calculated using the index variable, and the slice method is called with the range from index to index + chunkSize. The extracted chunk is then pushed into the chunks array.

The function continues to iterate until the index exceeds the length of the input array, ensuring that all elements are divided into equal-sized chunks. The resulting chunks array is returned as the output.

In the usage example provided, the chunkArray function is called with an example array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and a chunk size of 3. The resulting chunkedArray is logged to the console, showing the array divided into four equal-sized chunks: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading