JavaScript - Exclude some values in average calculation

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 14-Sep-2020 13:36:48
Advertisements