เรามีอาร์เรย์ที่บรรจุวัตถุหลายชิ้นที่ชื่อว่า นักเรียน วัตถุแต่ละชิ้นที่นักเรียนมีคุณสมบัติหลายอย่าง หนึ่งในนั้นคืออาร์เรย์ที่มีชื่อ เกรด -
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 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) // get a student's
highest grade
};
});
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