Giả sử chúng ta có object chứa điểm đánh giá theo các tiêu chí:
const rating = {
"overall": 92,
"atmosphere": 93,
"cleanliness": 94,
"facilities": 89,
"staff": 94,
"security": 92,
"location": 88,
"valueForMoney": 92
}Chúng ta cần viết hàm nhận vào object này và trả về cặp key-value có giá trị lớn nhất.
Với object này, đầu ra nên là:
const output = {
"staff": 94
};Ví dụ
Dưới đây là đoạn 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));Kết quả
Đoạn code sẽ in ra console:
{ cleanliness: 94 }