如何在 JavaScript 中查找对象数组中拥有最高值的对象?
javascriptweb developmentfront end technologyobject oriented programming
我们有一个数组,其中包含多个名为 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

