우리는 학생이라는 이름의 여러 객체를 포함하는 배열을 가지고 있으며, 각 학생에는 여러 속성이 있으며 그 중 하나는 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 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