-
-
Save ronsims2/3e1906929bf61965ca9cd606a1cd3785 to your computer and use it in GitHub Desktop.
Javascript array chunk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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