- 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
Calculating excluded average - JavaScript
Suppose we have an array of objects like this −
const arr = [ {val: 56, canUse: true}, {val: 16, canUse: true}, {val: 45, canUse: true}, {val: 76, canUse: false}, {val: 45, canUse: true}, {val: 23, canUse: false}, {val: 23, canUse: false}, {val: 87, canUse: true}, ];
We are required to write a JavaScript function that calculates the average of the val property of all those objects that have a boolean true set for the canUse flag.
Example
Following is the code −
const arr = [ {val: 56, canUse: true}, {val: 16, canUse: true}, {val: 45, canUse: true}, {val: 76, canUse: false}, {val: 45, canUse: true}, {val: 23, canUse: false}, {val: 23, canUse: false}, {val: 87, canUse: true}, ]; const excludedAverage = arr => { let count = 0, props = 0; for(let i = 0; i < arr.length; i++){ if(!arr[i].canUse){ continue; }; props++; count += arr[i].val; }; return (count) / (!props ? 1 : props); }; console.log(excludedAverage(arr));
Output
This will produce the following output in console −
49.8
- Related Articles
- Calculating quarterly and yearly average through JavaScript
- Calculating average of an array in JavaScript
- Calculating average of a sliding window in JavaScript
- Calculating average value per document with sort in MongoDB?
- Calculating the average for each subarray separately and then return the sum of all the averages in JavaScript
- Calculating factorial by recursion in JavaScript
- Calculating resistance of n devices - JavaScript
- Calculating Josephus Permutations efficiently in JavaScript
- Calculating median of an array JavaScript
- Calculating least common of a range JavaScript
- Calculating median of an array in JavaScript
- Euclidean Algorithm for calculating GCD in JavaScript
- Calculating the LCM of multiple numbers in JavaScript
- Calculating the sum of digits of factorial JavaScript
- Calculating a number from its factorial in JavaScript

Advertisements