在JavaScript中查找每个学生的n个最高分的平均值

假设,我们有一个对象数组,其中包含有关某些学生的信息以及他们在一段时间内的得分,如下所示:

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 },
];

我们需要编写一个JavaScript函数,该函数将一个数组作为第一个参数,并将一个数字(例如num)作为第二个参数。

然后,该函数应根据分数属性选择每个唯一学生的num个最高记录,并计算每个学生的平均值。如果没有足够的记录供任何学生使用,我们应该考虑他们的所有记录。

最后,该函数应返回一个对象,该对象具有学生ID作为键,而其平均分数作为值。

示例

为此的代码将是-

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));
输出结果

控制台中的输出将是-

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