Hi guys, actually I meneged to solve this problem, but it feels over complicated.
Can any of you advise me where and how can I make this more simple?
Thanks in advance for your effort! =)
Here is the code for the Chunky Monkey:
function chunkArrayInGroups(arr, size) {
var ans = [];
var i = 0;
while ( arr.length > 0 ) {
ans[i] = [];
//filling up the subArray
for (var k = 0; k < size; k++) {
ans[i].push(arr.shift());
// Return whatever we have, because no more elements left in [arr]
if (arr.length < 1) {
return ans;
}
}
i++;
}
return ans;
}
1 Like
Consider exactly what shift
does, as opposed to slice
. Then, consider how slice
differs from splice
, and think about how you could reduce the number of variables in play.
1 Like
Sorry for that, next time I’ll do it like that, but on the other hand, the title of this post is straight forward. But I know, rules are rules.
Thanks for the path, I reworked my code according your lead. Now it looks as I expected.
Here it is:
function chunkArrayInGroups(arr, size) {
var ans = [];
while (arr.length > 0) {
ans.push(arr.splice(0, size));
}
return ans;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);ste code here
Nice job! That’s almost exactly the same as the advanced solution on the guide
1 Like