我们有一个数组,其中包含几个名为student的对象,每个对象student具有多个属性,其中一个是名为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