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
Excluding extreme elements from average calculation in JavaScript
We need to write a JavaScript function that calculates the average of array elements while excluding the smallest and largest values. This is useful when you want to remove outliers from statistical calculations.
Problem Statement
Given an array of numbers, calculate the average excluding the minimum and maximum values. This helps eliminate extreme values that might skew the results.
Example
Let's implement a function that finds the excluded average:
const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
const findExcludedAverage = arr => {
const creds = arr.reduce((acc, val) => {
let { min, max, sum } = acc;
sum += val;
if(val > max){
max = val;
}
if(val < min){
min = val;
}
return { min, max, sum };
}, {
min: Infinity,
max: -Infinity,
sum: 0
});
const { max, min, sum } = creds;
return (sum - min - max) / (arr.length - 2);
};
console.log(findExcludedAverage(arr));
console.log("Original array:", arr);
console.log("Min value (excluded):", Math.min(...arr));
console.log("Max value (excluded):", Math.max(...arr));
5.714285714285714 Original array: [5, 3, 5, 6, 12, 5, 65, 3, 2] Min value (excluded): 2 Max value (excluded): 65
Alternative Approach Using Sort
Here's a simpler approach using array sorting:
const findExcludedAverageSimple = arr => {
if (arr.length <= 2) return 0;
const sorted = [...arr].sort((a, b) => a - b);
const middleElements = sorted.slice(1, -1);
const sum = middleElements.reduce((acc, val) => acc + val, 0);
return sum / middleElements.length;
};
const testArray = [10, 2, 8, 1, 9, 3];
console.log("Array:", testArray);
console.log("Excluded average:", findExcludedAverageSimple(testArray));
Array: [10, 2, 8, 1, 9, 3] Excluded average: 5.5
How It Works
The reduce method approach:
- Tracks minimum, maximum, and sum in a single pass
- Uses Infinity and -Infinity as initial values for comparison
- Subtracts min and max from total sum
- Divides by (array length - 2) since we exclude 2 elements
Edge Cases
// Handle arrays with 2 or fewer elements
const handleEdgeCases = arr => {
if (arr.length <= 2) {
console.log("Array too small for excluded average");
return 0;
}
return findExcludedAverage(arr);
};
console.log(handleEdgeCases([1, 2])); // 0
console.log(handleEdgeCases([5, 3, 8, 1])); // Average of [5, 3]
Array too small for excluded average 0 4
Conclusion
Excluding extreme values helps create more robust averages by removing outliers. The reduce approach is efficient with O(n) time complexity, while the sorting method is simpler to understand but has O(n log n) complexity.
