Last active
May 8, 2019 16:09
-
-
Save SauloSilva/9771598 to your computer and use it in GitHub Desktop.
Each slice javascript
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
// 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