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
Find the average of all elements of array except the largest and smallest - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns the average of its elements excluding the smallest and largest numbers.
Approach
The solution involves finding the minimum and maximum values, calculating the total sum, then computing the average of remaining elements after excluding min and max values.
Example
const arr = [1, 4, 5, 3, 5, 6, 12, 5, 65, 3, 2, 65, 9];
const findExcludedAverage = arr => {
const creds = arr.reduce((acc, val) => {
let { min, max, sum } = acc;
sum += val;
if(val > max){
max = val;
}
if(val
Array: [1, 4, 5, 3, 5, 6, 12, 5, 65, 3, 2, 65, 9]
Average (excluding min/max): 5.636363636363637
How It Works
The function uses reduce() to traverse the array once, simultaneously tracking:
- min: Smallest value (starts with Infinity)
- max: Largest value (starts with -Infinity)
- sum: Total of all elements
Finally, it calculates: (sum - min - max) / (arr.length - 2)
Alternative Approach
const findExcludedAverageSimple = arr => {
const min = Math.min(...arr);
const max = Math.max(...arr);
const sum = arr.reduce((total, num) => total + num, 0);
return (sum - min - max) / (arr.length - 2);
};
const testArray = [10, 20, 30, 40, 50];
console.log("Simple approach result:", findExcludedAverageSimple(testArray));
console.log("Expected: (20+30+40)/3 =", (20+30+40)/3);
Simple approach result: 30 Expected: (20+30+40)/3 = 30
Conclusion
Both approaches work effectively. The reduce method is more efficient with a single pass, while the Math.min/max approach is more readable. Choose based on your preference for performance vs. code clarity.
Advertisements
