- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Sort array based on min and max date in JavaScript?
- How to find the min/max element of an Array in JavaScript?
- Box plot with min, max, average and standard deviation in Matplotlib
- How to calculate average without max and min values in Excel?
- Min and max values of an array in MongoDB?
- Excluding extreme elements from average calculation in JavaScript
- Minimum removals from array to make max – min
- Min-Max Range Queries in Array in C++
- Get max and min values of an array in Arduino
- Min-Max Heaps
- Find max and min values in array of primitives using Java
- Symmetric Min-Max Heaps
- How to find Min/Max numbers in a java array?
- Find max and min values in an array of primitives using Java
- JavaScript: How to Find Min/Max Values Without Math Functions?

Advertisements