Chunk //JavaScript Repository

Description

Breaks an array into pieces.
Created: 2006.06.04

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/chunk [rev. #1]

function chunk(a, s){
    for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
        (x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
    return n;
}

Example (Example)

<script type="text/javascript">
//<![CDATA[

document.write(chunk([1,2,3,4,5,6,7], 3).join("<br />"));

//]]>
</script>

Help

chunk(input: Array, size: Integer): Array
Breaks an array into pieces.
input
array to be broken
test
maximum size of each piece

Rank (Votes: 59)

1.76