Last active
March 29, 2023 23:02
-
-
Save webinista/11240585 to your computer and use it in GitHub Desktop.
Array.prototype.chunk: Splits an array into an array of smaller arrays containing `groupsize` members
This file contains 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
/* | |
Split an array into chunks and return an array | |
of these chunks. | |
With kudos to github.com/JudeQuintana | |
This is an update example for code I originally wrote 5+ years ago before | |
JavaScript took over the world. | |
Extending native objects like this is now considered a bad practice, so use | |
the stuff between the curly braces and create your own function instead. | |
*/ | |
Array.prototype.chunk = function(groupsize){ | |
var sets = [], chunks, i = 0; | |
chunks = Math.ceil(this.length / groupsize); | |
while(i < chunks){ | |
sets[i] = this.splice(0, groupsize); | |
i++; | |
} | |
return sets; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is mine, with generators approch. usefull when you want deal with bunch of data but keep small memory usage. And you can imagine handle an unlimited data flow with it ^^.