Chunky Monkey (kinda stuck)

Chunky Monkey (kinda stuck)
0

#1

Tell us what’s happening:
Hey,

I really don’t understand why my code isn’t wielding the wanted result… could someone give me some insight? Thanks

Your code so far


var newArr = [];
function chunkArrayInGroups(arr, size) {
  // Break it up.
  let tmpArr = arr.splice(size, );  
  newArr.push(arr); 
  if (tmpArr.length > size) chunkArrayInGroups(tmpArr, size); 
  else newArr.push(tmpArr);  
  return newArr;  
}

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.

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


#2

What are you trying to do in this line?


#3

That line leaves the first segment in arr, and assigns the rest to tmpArr. Im really baffled as to why this doesnt work. Ive checked with console.log to see if im returning what i should and nothing seems wrong… ive checked and im definitely returning a multi dimensional array


#4

You have it backwards. After this line, tmpArr has [0, 1] in it and arr has [2, 3, 4, 5, 6, 7, 8].

Read about the return value in the splice documentation.


#5

#6

#7

I apologize for not looking closer at your code and testing it. You are correct about arr and tempArr values.


#8

Thats ok!

I just want to be sure about a few things: am I allowed to declare that variable I have outside of the function in this particular exercise? I need it since I do use recursion. And also since splice() returns and leaves separate arrays, when I push any of these into my global array it should create a multi dimensional array right?

Thanks in advance


#9

That is going to be a problem, because the tests run one after the other, so any global variables like that one are going to retain the value they had at the end of each previous test.

You are trying to use recursion here but your chunkArrayInGroups function does not have a termination condition to stop it from going forever.


#10

You are absolutely right… I probably have a bunch of empty arrays at the end of the final return array. Missing a return before the recursion call and some more tweaks. Thanks for the insight