Chúng ta có mảng chứa nhiều đối tượng tên là student, mỗi đối tượng student có nhiều thuộc tính, trong đó có mảng tên là 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 ]
}
];Cần tạo hàm lặp qua mảng student và tìm đối tượng student có điểm cao nhất trong mảng grades của nó.
Ví dụ
Mã thực hiện:
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);Kết quả
Kết quả in ra console:
Student 2 has the highest score of 90