Skip to content

Instantly share code, notes, and snippets.

@Angelfire
Created August 25, 2022 02:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Angelfire/f22e9e51e63302fb3215d2165016ea1e to your computer and use it in GitHub Desktop.
Save Angelfire/f22e9e51e63302fb3215d2165016ea1e to your computer and use it in GitHub Desktop.
Split a list into X chunks
function splitList(list, chunkSize) {
const groupSize = Math.ceil(list.length / chunkSize)
let chunked = []
for (let i = 0; i < list.length; i += groupSize) {
chunked.push(list.slice(i, i + groupSize))
}
return chunked
}
console.log(splitList([1, 2, 3, 4, 5, 6, 7, 8], 3)) // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ]
console.log(splitList([1, 2, 3, 4, 5, 6, 7, 8, 9], 2)) // [ [ 1, 2, 3, 4, 5 ], [ 6, 7, 8, 9 ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment