We are required to write a JavaScript function that takes in an array of Numbers and returns the smallest number from it using recursion.
Let’s say the following are our arrays −
const arr1 = [-2,-3,-4,-5,-6,-7,-8]; const arr2 = [-2, 5, 3, 0];
The code for this will be −
const arr1 = [-2,-3,-4,-5,-6,-7,-8]; const arr2 = [-2, 5, 3, 0]; const min = arr => { const helper = (a, ...res) => { if (!res.length){ return a; }; if (a < res[0]){ res[0] = a; }; return helper(...res); }; return helper(...arr); } console.log(min(arr1)); console.log(min(arr2));
Following is the output on console −
-8 -2