ภาพรวม
เรามีอาร์เรย์ที่เก็บอ็อบเจ็กต์นักเรียน แต่ละอ็อบเจ็กต์มีคุณสมบัติ grades เป็นอาร์เรย์:
const arr = [
{ name: "Student 1", grades: [65, 61, 67, 70] },
{ name: "Student 2", grades: [50, 51, 53, 90] },
{ name: "Student 3", grades: [0, 20, 40, 60] }
];
เราต้องสร้างฟังก์ชันวนลูปหาอ็อบเจ็กต์นักเรียนที่มีเกรดสูงสุดในอาร์เรย์ grades
ตัวอย่างโค้ด
const arr = [
{ name: "Student 1", grades: [65, 61, 67, 70] },
{ name: "Student 2", grades: [50, 51, 53, 90] },
{ name: "Student 3", grades: [0, 20, 40, 60] }
];
const highestGrades = arr.map((stud, ind) => {
return {
name: stud.name,
highestGrade: Math.max.apply(Math, stud.grades)
};
});
const bestStudent = highestGrades.sort((a, b) => {
return b.highestGrade - a.highestGrade;
})[0];
console.log(bestStudent.name + " has the highest score of " + bestStudent.highestGrade);
ผลลัพธ์ในคอนโซล
Student 2 has the highest score of 90