Skip to content
Advertisement

Splitting an array in equal parts

I am looking for a Javascript Algorithm to split an array into chunks, but avoiding any small left overs. For example:

JavaScript

But I want this:

JavaScript

So basically the output is spread over several arrays with a maximum number of elements passed in as second argument.

Advertisement

Answer

You should recalculate the size, which might need to be smaller than given. Then calculate from where the size should be one less for the remaining chunks.

So you will have potentially two different chunk sizes (which differ by 1). For both you can call the original _.chunk:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement