DEV Community

Discussion on: How to split arrays into equal-sized chunks

Collapse
 
marcobiedermann profile image
Marco Biedermann

Great post! Very detailed.
Instead of using the spread operator, you could also make use of Array.from. You can define the length by passing in an object and use the second argument to loop over it. No need to call Array.map on it

const chunkArray = (array, size: number) => {
  const numberOfChunks = Math.ceil(array.length / chunkSize)

  return Array.from(
    {
      length: numberOfChunks,
    },
    (_, index) => array.slice(index * chunkSize, (index + 1) * chunkSize)
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codefinity profile image
Manav Misra

🔥 Hot tip. Welcome to the community!

Collapse
 
domhabersack profile image
Dom Habersack

This is fantastic, thanks so much for sharing!