Computer >> Computer tutorials >  >> Programming >> Javascript

Finding average age from array of Objects using 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