Created
March 22, 2019 18:59
-
-
Save cms/e5b6d439bfec5beaa06e0dac7ec976bf to your computer and use it in GitHub Desktop.
array 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
// Using Array.prototype.reduce: | |
const getChunks = (array, size) => { | |
return array.reduce((acc, curr, i) => { | |
const pos = Math.floor(i/size); | |
acc[pos] = [...(acc[pos]||[]), curr]; | |
return acc | |
}, []) | |
} | |
// Using Array.from: | |
const getChunks = (array, size) => { | |
const length = Math.ceil(array.length / size) | |
return Array.from({ length }, (_v, i) => array.slice(i * size, (i * size) + size)); | |
} | |
// Using a copy of the array and Array.prototype.splice: | |
const getChunks = (array, size) => { | |
const a = [...array], result = [] | |
while(a.length > 0) { | |
result.push(a.splice(0, size)) | |
} | |
return result | |
} | |
/* | |
getChunks([1,2,3,4,5,6,7,8,9,0], 3) | |
(4) [Array(3), Array(3), Array(3), Array(1)] | |
0: (3) [1, 2, 3] | |
1: (3) [4, 5, 6] | |
2: (3) [7, 8, 9] | |
3: [0] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment