在 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 }
廣告