Created
August 25, 2022 02:11
-
-
Save Angelfire/f22e9e51e63302fb3215d2165016ea1e to your computer and use it in GitHub Desktop.
Split a list into X chunks
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
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