- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding smallest number using recursion in JavaScript
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
Advertisements