Partitioning in JavaScript [duplicate]

I think you will have to use a for loop, don't know of any inbuilt functions...

Try this function:

function splitarray(input, spacing)
{
    var output = [];

    for (var i = 0; i < input.length; i += spacing)
    {
        output[output.length] = input.slice(i, i + spacing);
    }

    return output;
}

Here's a recursive solution:

function partition(array, n) {
  return array.length ? [array.splice(0, n)].concat(partition(array, n)) : [];
}    

This takes advantage of the fact that Array#splice destructively remove the specified items, and returns them as the function value. Note that this will destroy the input array, leaving it empty.


If using Underscore.js, you can implement this with groupBy() and values()

function partition(items, size) {
    var result = _.groupBy(items, function(item, i) {
        return Math.floor(i/size);
    });
    return _.values(result);
}

(This is less ugly in CoffeeScript.)

jsFiddle: http://jsfiddle.net/MW3BS/


One more solution, with no external library :

function partition(items, size) {
    var p = [];
    for (var i=Math.floor(items.length/size); i-->0; ) {
        p[i]=items.slice(i*size, (i+1)*size);
    }
    return p;
}

Demonstration : http://jsfiddle.net/dystroy/xtHXZ/


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 );