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
Returning an array with the minimum and maximum elements JavaScript
Finding the minimum and maximum elements in a JavaScript array is a common task. This tutorial shows how to return both values in a single array using different approaches.
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
We need to write a function that finds the minimum and maximum elements and returns them as an array with minimum at index 0 and maximum at index 1.
Using Array.reduce() Method
The reduce() method provides an efficient way to traverse the array once and track both minimum and maximum values:
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
const minMax = (arr) => {
return arr.reduce((acc, val) => {
if(val < acc[0]){
acc[0] = val;
}
if(val > acc[1]){
acc[1] = val;
}
return acc;
}, [Infinity, -Infinity]);
};
console.log(minMax(arr));
[ 4, 545 ]
Using Math.min() and Math.max()
A simpler approach uses the built-in Math.min() and Math.max() methods with the spread operator:
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
const minMaxSimple = (arr) => {
return [Math.min(...arr), Math.max(...arr)];
};
console.log(minMaxSimple(arr));
[ 4, 545 ]
Using a For Loop
For better performance with very large arrays, a traditional for loop works efficiently:
const arr = [12, 54, 6, 23, 87, 4, 545, 7, 65, 18, 87, 8, 76];
const minMaxLoop = (arr) => {
let min = arr[0];
let max = arr[0];
for(let i = 1; i < arr.length; i++) {
if(arr[i] < min) min = arr[i];
if(arr[i] > max) max = arr[i];
}
return [min, max];
};
console.log(minMaxLoop(arr));
[ 4, 545 ]
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
Array.reduce() |
Good | Good | Low |
Math.min/max() |
Excellent | Good for small arrays | Higher (spread operator) |
For loop |
Good | Best for large arrays | Lowest |
Handling Edge Cases
Always check for empty arrays to avoid errors:
const minMaxSafe = (arr) => {
if(arr.length === 0) return [undefined, undefined];
return [Math.min(...arr), Math.max(...arr)];
};
console.log(minMaxSafe([]));
console.log(minMaxSafe([42]));
[ undefined, undefined ] [ 42, 42 ]
Conclusion
Use Math.min()/Math.max() for simplicity and readability. For large arrays, prefer the for loop approach for better performance. Always handle empty arrays to prevent runtime errors.
