สมมติว่าเรามีอาร์เรย์อ็อบเจกต์เก็บคะแนนนักเรียน:
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 }
];เราต้องเขียนฟังก์ชันที่รับอาร์เรย์นี้และคืนค่าอ็อบเจกต์ที่มี name และ total ของนักเรียนที่คะแนนสูงสุด
ผลลัพธ์ควรเป็น: { 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 }