Skip to content

Instantly share code, notes, and snippets.

@cms
Created Mar 22, 2019
Embed
What would you like to do?
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