สมมติว่าเรามีวัตถุหลายอย่างที่มีข้อมูลเกี่ยวกับนักเรียนบางคนและคะแนนที่พวกเขาทำในช่วงเวลาเช่นนี้ -
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 เป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันควรเลือกจำนวนระเบียนสูงสุดของนักเรียนแต่ละคนที่ไม่ซ้ำกันตามคุณสมบัติของคะแนนและคำนวณค่าเฉลี่ยสำหรับนักเรียนแต่ละคน หากมีบันทึกไม่เพียงพอสำหรับนักเรียน เราควรนำบันทึกทั้งหมดมาพิจารณา
และสุดท้าย ฟังก์ชันควรส่งคืนวัตถุที่มีรหัสนักเรียนเป็นคีย์ และให้คะแนนเฉลี่ยเป็นค่า
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
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 }