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 }