Created
March 2, 2020 15:03
-
-
Save Andy-set-studio/f32ee0bfcfb66279e18ca61d977c5d56 to your computer and use it in GitHub Desktop.
Split an array into sized chunks
This file contains 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
/** | |
* Takes an array and splits it into sized chunks | |
* that are <= the passed chunkSize param | |
* | |
* @param {Array} source Source array | |
* @param {Number} chunkSize The max size of each chunk | |
* @returns {Array} A 2d array of chunks | |
*/ | |
const splitArrayIntoChunks = (source, chunkSize) => { | |
if (!source.length) { | |
return []; | |
} | |
if (source.length <= chunkSize) { | |
return [source]; | |
} | |
return [source.slice(0, chunkSize)].concat(splitArrayIntoChunks(source.slice(chunkSize), chunkSize)); | |
}; | |
module.exports = splitArrayIntoChunks; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage