I need to get the highest score from this Array, but it kept giving me the [0] position and the highest which is 88 and 98
const classInfo = {
students: [
{ firstName: "Joe", lastName: "Smith", score: 88 },
{ firstName: "John", lastName: "Doe", score: 65 },
{ firstName: "Joel", lastName: "Garcia", score: 98 },
{ firstName: "Judy", lastName: "Johnson", score: 77 },
{ firstName: "Anne", lastName: "Dew", score: 88 },
]
};
let best_result //edited
for (let i = 0; i < classInfo.students.length; i ) {
if (classInfo.students[i].score > best_result) {
best_result = classInfo.students[i].score;
console.log(best_result);
}
CodePudding user response:
Maybe not the most efficient way, but you can set an array of scores and get the max value :)
const classInfo = {
students: [{
firstName: "Joe",
lastName: "Smith",
score: 88
},
{
firstName: "John",
lastName: "Doe",
score: 65
},
{
firstName: "Joel",
lastName: "Garcia",
score: 98
},
{
firstName: "Judy",
lastName: "Johnson",
score: 77
},
{
firstName: "Anne",
lastName: "Dew",
score: 88
},
]
};
let scores = [];
classInfo.students.map((student) => scores.push(student.score));
console.log(scores);
console.log(Math.max.apply(null, scores)); // credits : https://stackoverflow.com/a/1669222/4698373
CodePudding user response:
You should define best_result
variable outside of the loop, because if you define a variable inside a loop then for each iteration variable would get reinitialised.
const classInfo = {
students: [
{ firstName: "Joe", lastName: "Smith", score: 88 },
{ firstName: "John", lastName: "Doe", score: 65 },
{ firstName: "Joel", lastName: "Garcia", score: 98 },
{ firstName: "Judy", lastName: "Johnson", score: 77 },
{ firstName: "Anne", lastName: "Dew", score: 88 },
]
};
let best_result = 0;
for (let i = 0; i < classInfo.students.length; i ) {
if (classInfo.students[i].score > best_result) {
best_result = classInfo.students[i].score;
}
}
console.log(best_result);