Skip to content

Instantly share code, notes, and snippets.

@subimage
Created April 19, 2012 06:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save subimage/2419212 to your computer and use it in GitHub Desktop.
Save subimage/2419212 to your computer and use it in GitHub Desktop.
Javascript array chunk
// Splits an array into equal sized chunks
Array.prototype.chunk = function(pieces) {
pieces = pieces || 2;
var len = this.length;
var mid = (len/pieces);
var chunks = [];
var start = 0;
for(var i=0;i<pieces;i++) {
var last = start+mid;
if (!len%pieces >= i) {
last = last-1
}
chunks.push(this.slice(start,last+1) || []);
start = last+1;
}
return chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment