Average of array excluding min max JavaScript



We are required to write a JavaScript function that takes in an array of numbers. The function should calculate the average of the array, just excluding the largest and the smallest element of the array.

We will use the Array.prototype.reduce() method to calculate the sum of the array elements and at the same time find the greatest and smallest element.

Example

const arr = [2, 6, 5, 4, 6, 8, 8, 5, 6, 6, 9, 4, 1, 4, 6, 7];
const specialAverage = (arr = []) => {
   const { length } = arr;
   if(length <= 2){
      return 0;
   };
   const { sum, min, max } = 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: Number.MAX_VALUE,
      max: Number.MIN_VALUE,
      sum: 0
   });
   return (sum - min - max) / (length - 2);
};
console.log(specialAverage(arr));

Output

This will produce the following output −

5.5

Advertisements