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
Highest and lowest in an array JavaScript
In JavaScript, finding the difference between the highest and lowest values in an array is a common task. This article demonstrates multiple approaches to calculate this difference efficiently.
Using Math.max() and Math.min() with Spread Operator
The most straightforward approach uses the spread operator with Math.max() and Math.min():
const arr = [23, 54, 65, 76, 87, 87, 431, -6, 22, 4, -454];
const arrayDifference = (arr) => {
const max = Math.max(...arr);
const min = Math.min(...arr);
return max - min;
};
console.log("Array:", arr);
console.log("Difference:", arrayDifference(arr));
Array: [23, 54, 65, 76, 87, 87, 431, -6, 22, 4, -454] Difference: 885
Using forEach Loop
For better performance with large arrays, iterate through once to find both values:
const arr = [23, 54, 65, 76, 87, 87, 431, -6, 22, 4, -454];
const arrayDifference = (arr) => {
let min, max;
arr.forEach((num, index) => {
if (index === 0) {
min = num;
max = num;
} else {
min = Math.min(num, min);
max = Math.max(num, max);
}
});
return max - min;
};
console.log("Using forEach:", arrayDifference(arr));
Using forEach: 885
Using reduce() Method
A functional programming approach using reduce():
const arr = [23, 54, 65, 76, 87, 87, 431, -6, 22, 4, -454];
const arrayDifference = (arr) => {
const result = arr.reduce((acc, num) => ({
min: Math.min(acc.min, num),
max: Math.max(acc.max, num)
}), { min: arr[0], max: arr[0] });
return result.max - result.min;
};
console.log("Using reduce:", arrayDifference(arr));
Using reduce: 885
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Spread + Math methods | High | Good for small arrays | Simple, readable code |
| forEach loop | Medium | Best for large arrays | Performance-critical applications |
| reduce method | Medium | Good | Functional programming style |
Handling Edge Cases
Always validate input arrays to avoid errors:
const arrayDifference = (arr) => {
if (!arr || arr.length === 0) {
return 0;
}
if (arr.length === 1) {
return 0;
}
const max = Math.max(...arr);
const min = Math.min(...arr);
return max - min;
};
console.log("Empty array:", arrayDifference([]));
console.log("Single element:", arrayDifference([5]));
console.log("Normal array:", arrayDifference([1, 2, 3, 4, 5]));
Empty array: 0 Single element: 0 Normal array: 4
Conclusion
Use the spread operator with Math.max() and Math.min() for simplicity. For large arrays, prefer the forEach approach for better performance.
Advertisements
