# Chunky Monkey: I can't pass the last test

Tell us what’s happening:

I can’t pass the last test. What am I missing here?

``````
function chunkArrayInGroups(arr, size) {
// Break it up.
let newArr = [];
for(let i = 0; i < arr.length; i++) {
let arrs = arr.splice(0,size);
newArr.push(arrs);
}
if(arr.length === 0){
return newArr;
} else {
newArr.push(arr);
}
return newArr;
}

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

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36`.

you might be hitting a problem with your loop.
the for loop is generally better for iteration when you aren’t going to change the length of the array.

I haven’t parsed the logic, but I would suggest trying a while ( arr.length > 1) loop instead

1 Like

Hi,
Your loop logic is a little flawed. i < arr.length doesn’t seem to be a reasonable test for exit condition especially since i is increasing by one and arr.length is decreasing by whatever size is. Your loop is very likely to complete with a little piece of arr left over that still needs processing which you have tried to rectify with a if…else at the end but that doesn’t always work.

Try putting what you are doing into words.

Using the last test chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) as example I might think something like this

Do I have array to process? [0, 1, 2, 3, 4, 5, 6, 7, 8] Yes!
Then take off two elements [0,1] and push onto newArr
Do I have array to process? [2, 3, 4, 5, 6, 7, 8] Yes.
Take off two more and push onto newArr
Do I have array to process? [4, 5, 6, 7, 8] Yes.
Take off two more and push
Do I have array to process? [6, 7, 8] Yes.
Take off two more and push
Do I have array to process? [ 8] Yes.
Take off two more and push (OK really just one)
Do I have array to process? [ ] No
Then I’m done!
return newArr

Good luck

1 Like