Calculate Average of Given Properties in Array of Objects in JavaScript



We have an array of objects. Each object contains a few properties and one of these properties is age −

const people = [
   {
      name: 'Anna',
      age: 22
   }, {
      name: 'Tom',
      age: 34
   }, {
      name: 'John',
      age: 12
   }, {
      name: 'Kallis',
      age: 22
   }, {
      name: 'Josh',
      age: 19
   }
]

We have to write a function that takes in such an array and returns the average of all the ages present in the array.

Therefore, let’s write the code for this function −

Example

const people = [
   {
      name: 'Anna',
      age: 22
   }, {
      name: 'Tom',
      age: 34
   }, {
      name: 'John',
      age: 12
   }, {
      name: 'Kallis',
      age: 22
   }, {
      name: 'Josh',
      age: 19
   }
]
const findAverageAge = (arr) => {
   const { length } = arr;
   return arr.reduce((acc, val) => {
      return acc + (val.age/length);
   }, 0);
};
console.log(findAverageAge(people));

Output

The output in the console will be −

21.8
Updated on: 2020-08-24T09:42:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements