Created
August 24, 2018 10:21
-
-
Save atomize/871de3b109adc489e82ea9f36b450578 to your computer and use it in GitHub Desktop.
Returns an array with arrays of the given size.
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
/** | |
* 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