Skip to content

Instantly share code, notes, and snippets.

@minedun6
Forked from subimage/array_chunk.js
Created December 10, 2016 09:07
Show Gist options
  • Save minedun6/1467680d7ac05f2c1d75d110863a88bb to your computer and use it in GitHub Desktop.
Save minedun6/1467680d7ac05f2c1d75d110863a88bb 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