Skip to content

Instantly share code, notes, and snippets.

@cms
Created March 22, 2019 18:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cms/e5b6d439bfec5beaa06e0dac7ec976bf to your computer and use it in GitHub Desktop.
Save cms/e5b6d439bfec5beaa06e0dac7ec976bf to your computer and use it in GitHub Desktop.
array chunks
// 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