- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Excluding extreme elements from average calculation in JavaScript
We are required to write a JavaScript function that takes in an array of Number. Then the function should return the average of its elements excluding the smallest and largest Number.
Example
The code for this will be −
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));
Output
The output in the console −
8.666666666666666
Advertisements