Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find inside an array of objects the object that holds the highest value in JavaScript?
Finding the object with the highest value in an array of objects is a common task in JavaScript. This example demonstrates how to find the student with the highest grade from an array of student objects.
Sample Data
Let's start with an array of student objects, where each student has a name and an array of 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 ]
}
];
Method 1: Using map() and sort()
This approach first maps each student to their highest grade, then sorts to find the best:
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) => {
return {
name: stud.name,
highestGrade: Math.max(...stud.grades)
};
});
const bestStudent = highestGrades.sort((a, b) => {
return b.highestGrade - a.highestGrade;
})[0];
console.log(bestStudent.name + " has the highest score of " + bestStudent.highestGrade);
Student 2 has the highest score of 90
Method 2: Using reduce() (More Efficient)
A more efficient approach using reduce() to find the best student in a single pass:
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 bestStudent = arr.reduce((best, current) => {
const currentMax = Math.max(...current.grades);
const bestMax = Math.max(...best.grades);
return currentMax > bestMax ? current : best;
});
console.log(bestStudent.name + " has the highest score of " + Math.max(...bestStudent.grades));
Student 2 has the highest score of 90
Method 3: Finding Object with Maximum Property Value
For objects with a single numeric property, you can use this general pattern:
const products = [
{ name: "Laptop", price: 1200 },
{ name: "Phone", price: 800 },
{ name: "Tablet", price: 600 }
];
const mostExpensive = products.reduce((max, product) =>
product.price > max.price ? product : max
);
console.log("Most expensive:", mostExpensive.name, "$" + mostExpensive.price);
Most expensive: Laptop $1200
Comparison
| Method | Performance | Readability | Use Case |
|---|---|---|---|
| map() + sort() | Slower (two passes) | Good | When you need all highest values |
| reduce() | Faster (single pass) | Excellent | Finding single maximum object |
Conclusion
Use reduce() for finding the object with the highest value as it's more efficient. The map() + sort() approach is useful when you need to process all objects first.
