juliascoding - 5 months ago 7

Javascript Question

I am lerning recursion and would like to know whats wrong with my solution. I am trying to find the smallest numbers using recursion(I know using a loop etc is much easier, but as I am learning recursion, I try to write a recursive function for that). Thanks!

`function min(arr) {`

if (arr.length==1){

return arr[0];

}

else if(arr[0]>arr[1]) {

return min(arr.slice(1));

}

else {

min(arr[0]+ arr.slice(2));

}

}

min([-5,4,0,8,5]);

Answer

You need to use `concat`

to join the arrays and not `+`

. Try this:

```
function min(arr) {
if (arr.length==1){
return arr[0];
}
else if(arr[0]>arr[1]) {
return min(arr.slice(1));
}
else {
return min([arr[0]].concat(arr.slice(2)));
}
}
```

Here's a documentation link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

Source (Stackoverflow)

Comments