I tossed together a working solution to the Chunky Monkey challenge in the Basic Algorithm Scripting section using a while loop and splice and had a question regarding the while loop that seems to work but probably isn’t optimal…
function chunkArrayInGroups(arr, size) {
var chunkArray = [];
while(arr.length) {
chunkArray.push(arr.splice(0,size));
}
return chunkArray;
}
chunkArrayInGroups(["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"], 4);
The splice eats away the arr array as it pushes the chunks into chunkArray until the arr array length = 0 and thus the while loop becomes false and ends the loop. I assume this is in poor form and what would be a better option? For loop and cache the length initially?
Thanks!