I've added this solution to @dystroy's jspref here and it appears to run twice as fast as the other solutions. Edit: in Safari & Chrome but not Firefox
Here is functional style solution to add to the mix of answers here.
It is a higher order function called toPartitions
which returns a callback for underscore's reduce method or the native array reduce method.
Example usage:
[1,2,3,4,5,6,7,8,9].reduce( toPartitions( 3 ), [] );
The function:
function toPartitions ( size ) {
var partition = [];
return function ( acc, v ) {
partition.push( v );
if ( partition.length === size ) {
acc.push( partition );
partition = [];
}
return acc;
};
}
Like Clojure's partition it will not include a tail partition when there are not enough elements.
In your example you could do:
arrayALLPartionned = arrayAll.reduce( toPartitions( 3 ), [] ) );
If you don't want to use this with reduce
, but just have a function which takes an array and partition size you could do:
function partition ( arr, size ) {
return arr.reduce( toPartitions( size ), [] );
}
Therefore the solution would just be:
arrayALLPartionned = partition( arrayAll, 3 );