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
Returning the highest number from object properties value – JavaScript
When working with JavaScript objects, you might need to find the property with the highest value. For example, finding the highest rating from a property rating system.
Suppose we have an object that contains ratings of a property over some criteria like this:
const rating = {
"overall": 92,
"atmosphere": 93,
"cleanliness": 94,
"facilities": 89,
"staff": 94,
"security": 92,
"location": 88,
"valueForMoney": 92
}
We need to write a JavaScript function that takes such an object and returns the key-value pair with the highest value.
For this object, one possible output would be:
{ "cleanliness": 94 }
Using Object.values() and Math.max()
This approach extracts all values, finds the maximum, then locates the corresponding key:
const rating = {
"overall": 92,
"atmosphere": 93,
"cleanliness": 94,
"facilities": 89,
"staff": 94,
"security": 92,
"location": 88,
"valueForMoney": 92
};
const findHighest = obj => {
const values = Object.values(obj);
const max = Math.max(...values);
for (const key in obj) {
if (obj[key] === max) {
return { [key]: max };
}
}
};
console.log(findHighest(rating));
{ cleanliness: 94 }
Using Object.entries() Method
A more concise approach using Object.entries() and reduce():
const rating = {
"overall": 92,
"atmosphere": 93,
"cleanliness": 94,
"facilities": 89,
"staff": 94,
"security": 92,
"location": 88,
"valueForMoney": 92
};
const findHighestWithReduce = obj => {
const [key, value] = Object.entries(obj).reduce((max, current) =>
current[1] > max[1] ? current : max
);
return { [key]: value };
};
console.log(findHighestWithReduce(rating));
{ cleanliness: 94 }
Handling Multiple Maximum Values
If you need all properties with the maximum value (since "cleanliness" and "staff" both have 94):
const rating = {
"overall": 92,
"atmosphere": 93,
"cleanliness": 94,
"facilities": 89,
"staff": 94,
"security": 92,
"location": 88,
"valueForMoney": 92
};
const findAllHighest = obj => {
const max = Math.max(...Object.values(obj));
const result = {};
for (const [key, value] of Object.entries(obj)) {
if (value === max) {
result[key] = value;
}
}
return result;
};
console.log(findAllHighest(rating));
{ cleanliness: 94, staff: 94 }
Comparison
| Method | Returns | Performance |
|---|---|---|
| Object.values() + Loop | First maximum found | Good |
| Object.entries() + reduce() | First maximum found | Better |
| Find all maximums | All properties with max value | Good |
Conclusion
Use Object.entries() with reduce() for the most concise solution. If multiple properties share the maximum value and you need all of them, use the filtering approach to capture all maximum entries.
