Recursion function is not working properly

I want to divide an array into subarrays using recursion. The error i get is maximum call stack size exceeded. But there is a base case. I tried two base cases, but the error is the same

  • When start === arr.length-1 && end === arr.length

  • x.length === arr.lenght

const rec =(arr, index )=>{
let x =
let start = 0
let end= index
if ( start === arr.length-1 && end === arr.length){
return x
}

return rec(x.push(arr.slice(start+1,end+1)))
}

rec([4,8,9,8],1,)

You need to make the problem smaller or you will never reach the base case

Will you please give me an example

As example of what? The freeCodeCamp curriculum contains several examples of recursion if that’s what you mean?

Agreeing with what Jeremy is saying, but scanning over your code:

if ( start === arr.length-1 && end === arr.length)

Are you sure about your math there? Are you sure about the logic? Do both conditions need to be met?

If I’m right, then I guess I can guess that you didn’t put a log statement in there. That would have been my first instinct. Successful programmers are the ones that want to dig in and figure out what the problem is. Put some log statements in there to see if you can figure out what the problem is.

Thanks a lot for the advice. I think the problem is that everytime the function runs, a brand new variables are created. I will take into consideration your suggestion about math.

I don’t know because I still don’t know what it is trying to do. And you haven’t said what your investigation with the logging discovered.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.