Home > Blockchain >  javascript - find average of object records
javascript - find average of object records

Time:07-01

So i have this set of data:

   {
     year: '2001',
     quarter: 'q1',
     mathGrade: '5',
     itGrade: '6',
     litGrade: '7'
   },
   {
     year: '2001',
     quarter: 'q2',
     mathGrade: '5',
     itGrade: '4',
     litGrade: '1'
   }
 ]

And i need to find an average for each quarter for the 3 subjects in an object. 2001 Q1 = (7 6 5) / 3.

I have tried different loops but in the end i mess up and get wrong results.

How can this be done?

CodePudding user response:

you can do something like this

const calculateAverage = (data) => data.map(({year, quarter, ...rest}) => ({
  year,
  quarter,
  ...rest,
  average: Object.values(rest).reduce((res, n) => res   Number(n), 0) / Object.keys(rest).length,
}))

const data  = [ {
     year: '2001',
     quarter: 'q1',
     mathGrade: '5',
     itGrade: '6',
     litGrade: '7'
   },
   {
     year: '2001',
     quarter: 'q2',
     mathGrade: '5',
     itGrade: '4',
     litGrade: '1'
   }
 ]
console.log(calculateAverage(data))

CodePudding user response:

You can simply achieve this requirement by using Array.forEach() along with Array.reduce() method.

Live Demo :

const quarterWiseDetails = [{
  year: '2001',
  quarter: 'q1',
  mathGrade: '5',
  itGrade: '6',
  litGrade: '7'
}, {
  year: '2001',
  quarter: 'q2',
  mathGrade: '5',
  itGrade: '4',
  litGrade: '1'
}];

quarterWiseDetails.forEach(obj => {
    const { year, quarter, ...grades } = obj;
  const gradesCount = Object.keys(grades).length;
  const sum = (accumulator, curr) => parseInt(accumulator)   parseInt(curr);
  obj.average = Object.values(grades).reduce(sum) / gradesCount;
});

console.log(quarterWiseDetails);

  • Related