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
Find n highest values in an object JavaScript
Let's say, we have an object that describes various qualities of a football player like this ?
const qualities = {
defence: 82,
attack: 92,
heading: 91,
pace: 96,
dribbling: 88,
tenacity: 97,
vision: 91,
passing: 95,
shooting: 90
};
We wish to write a function that takes in such object and a number n (n ? no. of keys in object) and returns an object with n highest key value pairs.
Like for n = 2
Output should be ?
{
tenacity: 97,
pace: 96
}
Implementation
The complete code for this function will be ?
const qualities = {
defence: 82,
attack: 92,
heading: 91,
pace: 96,
dribbling: 88,
tenacity: 97,
vision: 91,
passing: 95,
shooting: 90
};
const pickHighest = (obj, num = 1) => {
const requiredObj = {};
if(num > Object.keys(obj).length){
return false;
};
Object.keys(obj).sort((a, b) => obj[b] - obj[a]).forEach((key, ind) =>
{
if(ind < num){
requiredObj[key] = obj[key];
}
});
return requiredObj;
};
console.log("Top 3 qualities:", pickHighest(qualities, 3));
console.log("Top 1 quality:", pickHighest(qualities, 1));
console.log("Top 5 qualities:", pickHighest(qualities, 5));
Output
The output in the console will be ?
Top 3 qualities: { tenacity: 97, pace: 96, passing: 95 }
Top 1 quality: { tenacity: 97 }
Top 5 qualities: { tenacity: 97, pace: 96, passing: 95, attack: 92, heading: 91 }
How It Works
The function uses Object.keys() to get all property names, then sorts them by their values in descending order using obj[b] - obj[a]. The forEach loop adds only the first num properties to the result object.
Alternative Approach Using Object.entries()
const pickHighestAlternative = (obj, num = 1) => {
if(num > Object.keys(obj).length) return false;
return Object.fromEntries(
Object.entries(obj)
.sort(([,a], [,b]) => b - a)
.slice(0, num)
);
};
console.log("Alternative approach:", pickHighestAlternative(qualities, 3));
Alternative approach: { tenacity: 97, pace: 96, passing: 95 }
Conclusion
Both approaches sort object entries by values and return the top n key-value pairs. The second method is more concise using Object.entries() and Object.fromEntries().
