Last active
January 3, 2018 09:23
-
-
Save eldyvoon/8c4f21f17ab2d5482afc79a20d9c8bc2 to your computer and use it in GitHub Desktop.
Split Chunk Array in JavaScript
This file contains 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
//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