- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements