# Basic Algorithms: Chunky Monkey

Basic Algorithms: Chunky Monkey
0

#1

Here is the solution I tried that didn’t work and returns [[“a”, “b”]]:

``````function chunkArrayInGroups(arr, size) {
var newArr = [];
for (var i = 0; i < arr.length; i+=size) {
var slice = arr.slice(i, i + size);
var push = newArr.push(slice);
return newArr;
}
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);
``````

But my solution is not far off from the intermediate solution:

``````function chunkArrayInGroups(arr, size) {
// Break it up.
var arr2 = [];
for (var i = 0; i < arr.length; i+=size) {
arr2.push(arr.slice(i , i+size));
}
return arr2;
}
``````

I am confused how mine is different than the intermediate. To me, they look like they should return the same, but mine doesn’t return the correct answer. Any insight as to why my code doesn’t work like I think it should? Thank you!

#2

Your code is returning `newArr` too early. What happens is that on the for-loop’s first run, it sees a `return` statement. That will cause the for-loop to immediately break, before it has the chance to iterate through the entire array.

#3

Does the “return” stop the loop?

#4

Yes. Whenever the code hits a return statement, it immediately stops execution of the function it’s in, even when in a for-loop.