Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Forked from SauloSilva/each_slice.js
Created May 2, 2019 11:11
Show Gist options
  • Save lbvf50mobile/ff000e0f130928e93b688ff511818ac3 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/ff000e0f130928e93b688ff511818ac3 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