Skip to content

Instantly share code, notes, and snippets.

@eldyvoon
Last active January 3, 2018 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eldyvoon/8c4f21f17ab2d5482afc79a20d9c8bc2 to your computer and use it in GitHub Desktop.
Save eldyvoon/8c4f21f17ab2d5482afc79a20d9c8bc2 to your computer and use it in GitHub Desktop.
Split Chunk Array in JavaScript
//specs
chunk([1,2,3,4], 2) // [[1,2][3,4]]
chunk([1,2,3,4,5], 2) // [[1,2],[3,4],[5]]
chunk([1,2,3,4,5], 10) // [[1,2,3,4,5]]
//solution 1
function chunk(array, size) {
const chunked = [];
for (let elem of array) {
const last = chunked[chunked.length - 1];
if (!last || last.length === size) {
chunked.push([elem]);
} else {
last.push(elem);
}
}
return chunked;
}
//solution 2
function chunk(array, size) {
const chunked = [];
let index = 0;
while(index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
}
return chunked;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment