Let's say that I have an Javascript array looking as following:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?
EDIT: @mblase75 added more concise code to the earlier answer while I was writing mine, so I recommend going with his solution.
You could use code like this:
Change the value of
arraySize
to change the maximum length of the smaller arrays.Ok, let's start with a fairly tight one:
Which is used like this:
Then we have this tight reducer function:
Which is used like this:
Since a kitten dies when we bind
this
to a number, we can do manual currying like this instead:Which is used like this:
Then the still pretty tight function which does it all in one go:
I just wrote this with the help of a groupBy function.
Here's my approach using Coffeescript list comprehension. A great article detailing comprehensions in Coffeescript can be found here.
ES6 one-line approach based on
Array.prototype
reduce
andpush
methods:I changed BlazeMonger's slightly to use for a jQuery object..