Chunky Monkey Question can't Pass Test

Tell us what’s happening:

I think I solved the challenge correctly, but I was not able to pass the test. The results I got should be correct, does anyone know where the problem might be?

Thanks a lot.

Your code so far


function chunkArrayInGroups(arr, size) {
  // Break it up.
  if (size>=arr.length){
    arrglo.push(arr);
    console.log(arrglo)
    return arrglo;
  }
  else{
    let arr1=arr.slice(0,size);
    let arr2=arr.slice(size);
    
    arrglo.push(arr1);
    console.log(arrglo)
    return chunkArrayInGroups(arr2,size);
  }
}

let arrglo=[];


let a=chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);
console.log(a)

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey

The line above is the culprit. Using a global variable in general is never a good idea, because you don’t know how other code (in this case the FCC tests) are affecting it.

The FCC tests use all the code you have written and run each test as a separate call to your function. This mean, that between each test, arrglo is not reset back to an empty array each time.

You will need to slightly rethink your algorithm for this challenge to avoid this issue.

HINT: You only have to change the following line to get all the test to pass:

return chunkArrayInGroups(arr2,size);

Hi Randell,

Thanks for the reply, but I’m not very sure what kind of change can be made to address the problem, you mind giving me some ideas? Most importantly i’m not sure what the problem is. I tried to run it in the browser but it gave me many arrays instead of just one 2d array. I tried to remove “return” in the line you mentioned and add another line of “return arrglo”, it seemed to have worked in the browser but still could not pass the test.

You are using recursion here, so need to return the current value of arrglo with the result of chunkArrayInGroups(arr2,size) concatenated to it. There are a few different ways to accomplish this.