Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาค่าเฉลี่ย n คะแนนสูงสุดของแต่ละนักเรียนใน JavaScript

สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ที่มีข้อมูลนักเรียนและคะแนน:

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

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ดังกล่าวเป็นอาร์กิวเมนต์แรก และตัวเลข num เป็นอาร์กิวเมนต์ที่สอง ฟังก์ชันต้องเลือก num เรคคอร์ดสูงสุดของแต่ละนักเรียนตามคะแนน และคำนวณค่าเฉลี่ย ถ้าเรคคอร์ดไม่พอ ให้เอาทั้งหมด แล้วคืนอ็อบเจ็กต์ที่มี id เป็น key และคะแนนเฉลี่ยเป็น value

ตัวอย่างโค้ด

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}