

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Sort array based on min and max date in JavaScript?
- How to find the min/max element of an Array in JavaScript?
- Min-Max Heaps
- Box plot with min, max, average and standard deviation in Matplotlib
- Excluding extreme elements from average calculation in JavaScript
- Min and max values of an array in MongoDB?
- Get max and min values of an array in Arduino
- Symmetric Min-Max Heaps
- Min-Max Range Queries in Array in C++
- Find max and min values in array of primitives using Java
- Use of min() and max() in Python
- max() and min() in Python
- Find Max Slice Of Array | JavaScript
- Find max and min values in an array of primitives using Java
- How to find Min/Max numbers in a java array?
Advertisements