DEV Community

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

Collapse
 
alimobasheri profile image
MirAli Mobasheri

Thanks for sharing, Dom. It was an interesting read.
I was curious to achieve the same results using Array.reduce.

This is the solution I came up with:

const chunkArray = (array, chunkSize) => 
    array.reduce((chunks, value, index) => {
        return index % chunkSize === 0 ?
            [...chunks, [value]] :
            chunks.map((chunk, idx) => 
                idx === chunks.length-1 ?
                    chunk.concat(value) :
                    chunk
            )
    }, [])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
domhabersack profile image
Dom Habersack

Awesome! I hadn’t even considered using reduce for this. 👏