Skip to content

Instantly share code, notes, and snippets.

@SauloSilva
Last active May 8, 2019 16:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save SauloSilva/9771598 to your computer and use it in GitHub Desktop.
Save SauloSilva/9771598 to your computer and use it in GitHub Desktop.
Each slice javascript
// without callback
Array.prototype.eachSlice = function (size){
this.arr = []
for (var i = 0, l = this.length; i < l; i += size){
this.arr.push(this.slice(i, i + size))
}
return this.arr
};
[1, 2, 3, 4, 5, 6].eachSlice(2)
// output
/* [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] */
// with callback
Array.prototype.eachSlice = function (size, callback){
for (var i = 0, l = this.length; i < l; i += size){
callback.call(this, this.slice(i, i + size))
}
};
[1, 2, 3, 4, 5, 6].eachSlice(2, function(slice) {
console.log(slice)
})
// output
/*
[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment