 # Chunky Monkey : Using Recursion

Tell us what’s happening:
Sorry to interrupt but I think you all can help me…I want to know how the recursion tree of this solution will form.
Because I want to understand how recursion is happening in this case…

Thanks if anyone can help…( sleeping:

``````
function chunkArrayInGroups(arr, size) {
if (arr.length <= size){
return [arr];
}
else {
return [arr.slice(0,size)].concat(chunkArrayInGroups(arr.slice(size),size));
}
}

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

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

Things in parentheses always go first, that’s what will allow recursion to happen

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

1° iteration -> skips the if and goes into else, returns `[["a", "b"]].concat(chunkArrayInGroups(["c", "d"], 2))`
2° iteration -> enters the if, returns `[["c, "d"]]`

Then it goes backwards:

2° iteration -> returned `[["c", "d"]]`
1° iteration -> second iteration value goes into our concat `[["a", "b"]].concat([["c", "d"]])`, which returns `[["a", "b"], ["c", "d"]]`.

Not sure if I cleared the information or make it worse? This is actually a really good example of recursion, first you must make sure you understand exactly what `slice` and `concat` do, so you can worry only about the recursion. Second, every recursion must have an end condition, in our case is the if: `if (arr.length <= size){`. Third, imagine you are the compiler, go line by line thinking or writing exactly what the algorithm is doing.

1 Like

Thanks ( I like your explanation and understand the logic behind it…