Skip to content

Instantly share code, notes, and snippets.

@Andy-set-studio
Created March 2, 2020 15:03
Show Gist options
  • Save Andy-set-studio/f32ee0bfcfb66279e18ca61d977c5d56 to your computer and use it in GitHub Desktop.
Save Andy-set-studio/f32ee0bfcfb66279e18ca61d977c5d56 to your computer and use it in GitHub Desktop.
Split an array into sized chunks
/**
* 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;
@Andy-set-studio
Copy link
Author

Example usage

const source = ['hello', 'I', 'am', 'an', 'array', '🙂'];
const chunks = splitArrayIntoChunks(source, 2);

// Result 
[['hello', 'I'], ['am', 'an'], ['array', '🙂']]

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