如何在 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
廣告