Skip to content

Instantly share code, notes, and snippets.

@sofakingworld
Last active October 16, 2017 13:45
Show Gist options
  • Save sofakingworld/03fc66c84d4cda1f70840b803b7d4b8b to your computer and use it in GitHub Desktop.
Save sofakingworld/03fc66c84d4cda1f70840b803b7d4b8b to your computer and use it in GitHub Desktop.
JavaScript analog of EachSlice from Ruby
Array.prototype.eachSlice = function(size=1) {
return Array(Math.ceil(this.length / size))
.fill()
.map(( _, idx) => {
return this.slice(idx * size, (1 + idx) * size)
})
}
@sofakingworld
Copy link
Author

sofakingworld commented Oct 15, 2017

arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]
arr.eachSlice(3); // => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10, 11, 12 ], [ 13 ] ]

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