Skip to content

Instantly share code, notes, and snippets.

@impeto
Created January 31, 2016 16:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save impeto/8cb79e6bb0a0d9bb18ff to your computer and use it in GitHub Desktop.
Save impeto/8cb79e6bb0a0d9bb18ff to your computer and use it in GitHub Desktop.
Adds method `chunk` to the array class similar to Eloquent Collection's chunk method
(function() {
Array.prototype.chunk = function (chunkSize) {
var n = this.length;
if (chunkSize >= n) {
return [this];
}
if (n == 0) {
return [];
}
var r = n % chunkSize;
var q = (n - r) / chunkSize;
var result = [];
for (var i = 0; i <= q; i++) {
result.push(this.slice(i * chunkSize, i * chunkSize + chunkSize));
}
return result;
};
})();
@shobankr
Copy link

Thanks for the snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment