JavaScript
// Method 1: Using Math.max and Math.min with spread operator
let numbers = [10, 5, 20, 15, 8, 25];
let max = Math.max(...numbers);
let min = Math.min(...numbers);
console.log("Array:", numbers);
console.log("Maximum:", max);
console.log("Minimum:", min);
// Method 2: Using for loop
function findMaxMin(arr) {
if (arr.length === 0) return { max: null, min: null };
let max = arr[0];
let min = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
return { max, min };
}
let result = findMaxMin([10, 5, 20, 15, 8]);
console.log("\nUsing loop:", result);
// Method 3: Using reduce
function findMaxMinReduce(arr) {
return arr.reduce((acc, num) => {
acc.max = Math.max(acc.max, num);
acc.min = Math.min(acc.min, num);
return acc;
}, { max: arr[0], min: arr[0] });
}
console.log("\nUsing reduce:", findMaxMinReduce([3, 7, 2, 9, 1]));
// Method 4: Using sort
function findMaxMinSort(arr) {
let sorted = [...arr].sort((a, b) => a - b);
return {
min: sorted[0],
max: sorted[sorted.length - 1]
};
}
console.log("\nUsing sort:", findMaxMinSort([12, 4, 8, 19, 3]));Output
Array: [ 10, 5, 20, 15, 8, 25 ]
Maximum: 25
Minimum: 5
Using loop: { max: 20, min: 5 }
Using reduce: { max: 9, min: 1 }
Using sort: { min: 3, max: 19 }This program demonstrates different methods to find maximum and minimum values in an array.
Method 1: Math.max/min with Spread
Using ES6 spread operator:
javascriptlet max = Math.max(...numbers); let min = Math.min(...numbers);
Spread Operator (...):
- Expands array into individual arguments
Math.max(...[1,2,3])→Math.max(1,2,3)- Cleanest and most concise
Method 2: For Loop
Iterative approach:
javascriptlet max = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; }
Pros:
- Easy to understand
- O(n) time complexity
- Works with any array
Method 3: Reduce
Functional approach:
javascriptarr.reduce((acc, num) => { acc.max = Math.max(acc.max, num); acc.min = Math.min(acc.min, num); return acc; }, { max: arr[0], min: arr[0] });
Reduce Method:
- Accumulates values into single result
- Takes accumulator and current value
- Returns final accumulated value
Method 4: Sort
Sort array and get first/last:
javascriptlet sorted = [...arr].sort((a, b) => a - b); return { min: sorted[0], max: sorted[sorted.length - 1] };
Note: Creates copy with spread to avoid mutating original
Time Complexity:
- Spread/Math: O(n)
- Loop: O(n)
- Reduce: O(n)
- Sort: O(n log n) - Less efficient!
When to Use:
-
Spread/Math: Simplest, modern
-
Loop: Learning, custom logic
-
Reduce: Functional style
-
Sort: Avoid for this use case