在 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)作为第二个参数。

然后,该函数应根据 score 属性选择每个唯一学生的 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 }

更新于: 2021年2月26日

499 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.