Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tính trung bình top N điểm của mỗi học sinh trong JavaScript

Cho mảng object {id, score}. Viết hàm lấy num điểm cao nhất của mỗi học sinh, tính trung bình, trả về object {id: average}.

Ví dụ: với num=5 → {'231':193, '233':200} (tổng 5 điểm cao nhất).

Ví dụ

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((a, v) => a + v);
  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));

Kết quả

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