Find Object with Highest Value in Array of Objects 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: 2020-11-20T13:50:31+05:30

702 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements