

- 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
JavaScript - Exclude some values in average calculation
Let’s say, we have an array of objects like this −
data = [ {"Age":26,"Level":8}, {"Age":37,"Level":9}, {"Age":32,"Level":5}, {"Age":31,"Level":11}, {"Age":null,"Level":15}, {"Age":null,"Level":17}, {"Age":null,"Level":45} ];
We are required to write a JavaScript function that calculates the average level for all the objects that have a truthy value for age property
Let’s write the code for this function −
Example
Following is the code −
data = [ {"Age":26,"Level":8}, {"Age":37,"Level":9}, {"Age":32,"Level":5}, {"Age":31,"Level":11}, {"Age":null,"Level":15}, {"Age":null,"Level":17}, {"Age":null,"Level":45} ]; const findAverage = arr => { const creds = arr.reduce((acc, val) => { const { Age, Level } = val; let { count, sum } = acc; if(Age){ count += 1; sum += Level; }; return { count, sum }; }, { count: 0, sum: 0 }); return (creds.sum)/(creds.count); }; console.log(findAverage(data));
Output
Following is the output in the console −
8.25
- Related Questions & Answers
- Excluding extreme elements from average calculation in JavaScript
- MySQL query to exclude some of the values from the table
- MongoDB collection query to exclude some fields in find()?
- How to exclude certain values from randomly generated array JavaScript
- Exclude some ID records from a list and display rest in MySQL
- Calculating excluded average - JavaScript
- Using Calculation views inside another calculation view in SAP HANA
- MySQL query to exclude values having specific last 3 digits
- Find consecutive elements average JavaScript
- Write a program in Python to perform average of rolling window size 3 calculation in a given dataframe
- Array some() function in JavaScript
- JavaScript Array some() function
- Calculating average of an array in JavaScript
- Average with the Reduce Method in JavaScript
- Determine whether there is a pair of values in the array where the average of the pair equals to the target average in JavaScript
Advertisements