Finding average of n top marks of each student in JavaScript


Suppose, we have an array of objects that contains information about some students and the marks scored by them over a period of time like this −

const marks = [
   { id: 231, score: 34 },
   { id: 233, score: 37 },
   { id: 231, score: 31 },
   { id: 233, score: 39 },
   { id: 231, score: 44 },
   { id: 233, score: 41 },
   { id: 231, score: 38 },
   { id: 231, score: 31 },
   { id: 233, score: 29 },
   { id: 231, score: 34 },
   { id: 233, score: 40 },
   { id: 231, score: 31 },
   { id: 231, score: 30 },
   { id: 233, score: 38 },
   { id: 231, score: 43 },
   { id: 233, score: 42 },
   { id: 233, score: 28 },
   { id: 231, score: 33 },
];

We are required to write a JavaScript function that takes in one such array as the first argument and a number, say num, as the second argument.

The function should then pick num highest records of each unique student according to the score property and calculate average for each student. If there are not enough records for any student, we should take all of their records into consideration.

And finally, the function should return an object that has the student id as key and their average score as the value.

Example

The code for this will be −

 Live Demo

const marks = [
   { id: 231, score: 34 },
   { id: 233, score: 37 },
   { id: 231, score: 31 },
   { id: 233, score: 39 },
   { id: 231, score: 44 },
   { id: 233, score: 41 },
   { id: 231, score: 38 },
   { id: 231, score: 31 },
   { id: 233, score: 29 },
   { id: 231, score: 34 },
   { id: 233, score: 40 },
   { id: 231, score: 31 },
   { id: 231, score: 30 },
   { id: 233, score: 38 },
   { id: 231, score: 43 },
   { id: 233, score: 42 },
   { id: 233, score: 28 },
   { id: 231, score: 33 },
];
const calculateHighestAverage = (marks = [], num = 1) => {
   const findHighestSum = (arr = [], upto = 1) => arr
      .sort((a, b) => b - a)
      .slice(0, upto)
      .reduce((acc, val) => acc + val);
      const res = {};
   for(const obj of marks){
      const { id, score } = obj;
      if(res.hasOwnProperty(id)){
         res[id].push(score);
      }else{
         res[id] = [score];
      }
   };
   for(const id in res){
      res[id] = findHighestSum(res[id], num);
   };
   return res;
};
console.log(calculateHighestAverage(marks, 5));
console.log(calculateHighestAverage(marks, 4));
console.log(calculateHighestAverage(marks));

Output

And the output in the console will be −

{ '231': 193, '233': 200 }
{ '231': 159, '233': 162 }
{ '231': 44, '233': 42 }

Updated on: 26-Feb-2021

423 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements