How to find inside an array of objects the object that holds the highest value in JavaScript?


We have an array that holds several objects named student, each object student has several properties, one of which is an array named 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 ]
   }
];

We need to create a function that loops through the student's array and finds which student object has the highest grade inside its grades array.

Example

The code for this will be −

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);

Output

And the output in the console will be −

Student 2 has the highest score of 90

Updated on: 20-Nov-2020

570 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements