
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Finding Average Age from Array of Objects in JavaScript
Problem
We are required to write a JavaScript function that takes in an object that contains data about some people.
Our function should simply find the average of the age property for those people.
Example
Following is the code −
const people = [ { fName: 'Ashish', age: 23 }, { fName: 'Ajay', age: 21 }, { fName: 'Arvind', age: 26 }, { fName: 'Mahesh', age: 28 }, { fName: 'Jay', age: 19 }, ]; const findAverageAge = (arr = []) => { const { sum, count } = arr.reduce((acc, val) => { let { sum, count } = acc; sum += val.age; count++; return { sum, count }; }, { sum: 0, count: 0 }); return (sum / (count || 1)); }; console.log(findAverageAge(people));
Output
23.4
Advertisements