Skip to content

Instantly share code, notes, and snippets.

@atomize
Created August 24, 2018 10:21
Show Gist options
  • Save atomize/871de3b109adc489e82ea9f36b450578 to your computer and use it in GitHub Desktop.
Save atomize/871de3b109adc489e82ea9f36b450578 to your computer and use it in GitHub Desktop.
Returns an array with arrays of the given size.
/**
* Returns an array with arrays of the given size.
*
* @param myArray {Array} Array to split
* @param chunkSize {Integer} Size of every group
*
* https://binbytes.com/blog/split-an-array-into-chunks-of-a-given-size-in-javascript
*/
function chunkArray(myArray, chunk_size) {
let results = [];
while (myArray.length) {
results.push(myArray.splice(0, chunk_size))
}
return results;
}
// Usage
// Split in group of 3 items
var result = chunkArray([1,2,3,4,5,6,7,8], 3)
// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment