Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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];
Recursive Approach
The recursive solution uses a helper function that compares the first element with the rest of the array:
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
-8
-2
How It Works
The algorithm works by:
- Base case: When only one element remains, return it
- Recursive case: Compare the first element with the second, replace the second with the smaller value, and recurse with the remaining elements
-
Spread operator: Uses
...arrto pass array elements as individual arguments
Alternative Recursive Implementation
Here's a more straightforward recursive approach:
const findMin = (arr, index = 0) => {
// Base case: last element
if (index === arr.length - 1) {
return arr[index];
}
// Recursive case: compare current with minimum of rest
const minOfRest = findMin(arr, index + 1);
return arr[index]
-8
-2
Comparison
| Method | Approach | Memory Usage |
|---|---|---|
| Helper Function | Uses spread operator and parameter modification | Higher (creates new arrays) |
| Index-based | Uses index parameter to track position | Lower (no array copying) |
Conclusion
Both recursive approaches successfully find the minimum value. The index-based method is more memory-efficient, while the helper function approach demonstrates advanced JavaScript features like spread syntax.
Advertisements
