สมมติว่าเรามีชุดของวัตถุที่มีข้อมูลเกี่ยวกับคะแนนของนักเรียนบางคนในการทดสอบ -
const students = [
{ name: 'Andy', total: 40 },
{ name: 'Seric', total: 50 },
{ name: 'Stephen', total: 85 },
{ name: 'David', total: 30 },
{ name: 'Phil', total: 40 },
{ name: 'Eric', total: 82 },
{ name: 'Cameron', total: 30 },
{ name: 'Geoff', total: 30 }
]; เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวและส่งกลับวัตถุที่มีชื่อและผลรวมของนักเรียนที่มีมูลค่ารวมสูงสุด
ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็น −
{ name: 'Stephen', total: 85 } ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const students = [
{ name: 'Andy', total: 40 },
{ name: 'Seric', total: 50 },
{ name: 'Stephen', total: 85 },
{ name: 'David', total: 30 },
{ name: 'Phil', total: 40 },
{ name: 'Eric', total: 82 },
{ name: 'Cameron', total: 30 },
{ name: 'Geoff', total: 30 }
];
const pickHighest = arr => {
const res = {
name: '',
total: -Infinity
};
arr.forEach(el => {
const { name, total } = el;
if(total > res.total){
res.name = name;
res.total = total;
};
});
return res;
};
console.log(pickHighest(students)); ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้บนคอนโซล -
{ name: 'Stephen', total: 85 }