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
Find the difference of largest and the smallest number in an array without sorting it in JavaScript
We have an array of Numbers that are arranged in pure random order. Our job is to write a function that takes in one such array of Numbers and returns the difference of greatest and smallest numbers present in it, but without sorting the array.
We will use the Array.prototype.reduce() function to pick the smallest and greatest numbers from the array and later will return their difference.
Using Array.reduce() Method
The reduce() method allows us to iterate through the array once and track both maximum and minimum values simultaneously:
const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3];
const findDifference = arr => {
if(!arr.length){
return 0;
}
const creds = arr.reduce((acc, val) => {
let { max, min } = acc;
if(val > max){
max = val;
};
if(val < min){
min = val;
};
return { max, min };
}, {
max: -Infinity,
min: Infinity
});
return creds.max - creds.min;
};
console.log(findDifference(arr));
232
Using Math.max() and Math.min()
A simpler approach uses built-in Math functions with the spread operator:
const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3];
const findDifferenceSimple = arr => {
if(!arr.length) return 0;
const max = Math.max(...arr);
const min = Math.min(...arr);
return max - min;
};
console.log(findDifferenceSimple(arr));
console.log(`Max: ${Math.max(...arr)}, Min: ${Math.min(...arr)}`);
232 Max: 234, Min: 2
Using For Loop Method
For better performance with large arrays, use a simple loop:
const arr = [23, 65, 67, 23, 2, 6, 87, 23, 45, 65, 3, 234, 3];
const findDifferenceLoop = arr => {
if(!arr.length) return 0;
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;
};
console.log(findDifferenceLoop(arr));
232
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| Array.reduce() | Moderate | Good | Higher (creates objects) |
| Math.max/min() | High | Good (small arrays) | Higher (spread operator) |
| For Loop | High | Best | Lowest |
Conclusion
All three methods avoid sorting and find the difference in O(n) time. Use Math.max/min() for simplicity, or the for loop for optimal performance with large arrays.
