如何在 JavaScript 的对象数组中查找具有最高值的对象?
我们有一个包含多个名为 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 ] } ];
我们需要创建一个函数,该函数遍历 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 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
广告