- 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
Returning the highest number from object properties value – JavaScript
Suppose, we have an object that contains rating 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 are required to write a JavaScript function that takes in one such object and returns the key value pair that has the highest value.
For example, for this very object, the output should be −
const output = { "staff": 94 };
Example
Following is the code −
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.apply(Math, values); for(key in obj){ if(obj[key] === max){ return { [key]: max }; }; }; }; console.log(findHighest(rating));
Output
This will produce the following output in console −
{ cleanliness: 94 }
Advertisements
To Continue Learning Please Login
Login with Google