gpt4 book ai didi

javascript - 如何在对象数组中找到具有最高值的对象?

转载 作者:行者123 更新时间:2023-12-03 04:28:39 25 4
gpt4 key购买 nike

我有一个数组,其中包含多个名为student的对象,每个对象student都有多个属性,其中之一是名为grades的数组。

我需要创建一个函数,循环遍历学生数组并查找哪个学生对象在其成绩数组中成绩最高。

目前我能够找到最高分,但无法理解如何追溯到它属于哪个学生。

以下是该函数的片段:

function bestStudent() {
var bestGrade = 0;
var student;
for(i=0; i < studentArr.length; i++) {
var student = studentArr[i];
grades = student.grades;
for(g = 0; g <grades.length; g++){
if(grades[g] > bestGrade) {
bestGrade = grades[g];
}
}

}
}

最佳答案

总体思路如下:您可以首先将学生数组及其成绩映射到学生数组及其最高成绩,以便于使用并避免多次查找最大成绩计算,并且然后找到最大的学生的最高成绩。

举个例子:

var students = [
{
name: "Student 1",
grades: [ 65, 61, 67, 70 ]
},
{
name: "Student 2",
grades: [ 50, 51, 53, 90 ]
},
{
name: "Student 3",
grades: [ 0, 20, 40, 60 ]
}
];

var highestGrades = students.map(function(stud, ind) {
// return a student's name and his highest grade (1)
return {
name: stud.name,
highestGrade: Math.max.apply(Math, stud.grades) // get a student's highest grade
};

// or return index and use it to access original value: (2)
// return {
// index: ind,
// highestGrade: Math.max.apply(Math, stud.grades)
// };

// or return the whole student: (3)
// return {
// student: stud,
// highestGrade: Math.max.apply(Math, stud.grades)
// };

// or just add 'highestGrade' property to object without modifying
// if it's ok for you to have intermediate properties in your object: (4)
// stud.highestGrade = Math.max.apply(Math, stud.grades);
// return stud;
});

// this can be done in O(n), not in O(N * logN) if required:
var bestStudent = highestGrades.sort(function(a, b) {
return b.highestGrade - a.highestGrade;
})[0]; // sort by highest grade desc and return the first (the best) one

// Here we have bestStudent with his name according to map function:
console.log(bestStudent.name + " has the highest score of " + bestStudent.highestGrade); // (1)
// console.log(students[bestStudent.index].name + " has the highest score of " + bestStudent.highestGrade); // (2)
// console.log(bestStudent.student.name + " has the highest score of " + bestStudent.highestGrade); // (3)
// console.log(bestStudent.name + " has the highest score of " + bestStudent.highestGrade); // (4)

您可以重写此代码,以便它返回整个学生作为结果、或其索引或其特定属性。如果您的对象可以具有额外的中间属性,您还可以将 highestGrade 属性添加到原始对象。这取决于你,这个想法不会改变:)

这段代码比较长,但是可读性强,并且让算法的思路清晰,对于初学者来说非常重要。
如果您和您的团队喜欢更短但更复杂的代码,那么您可以轻松重写它。
就像这样:

var students = [
{
name: "Student 1",
grades: [ 65, 61, 67, 70 ]
},
{
name: "Student 2",
grades: [ 50, 51, 53, 90 ]
},
{
name: "Student 3",
grades: [ 0, 20, 40, 60 ]
}
];

var bestStudent = students.map(function(stud) {
stud.highestGrade = Math.max.apply(Math, stud.grades);
return stud;
}).sort(function(a, b) {
return b.highestGrade - a.highestGrade;
})[0];

console.log(bestStudent);

关于javascript - 如何在对象数组中找到具有最高值的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43590551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com