Get Key with Highest Value from a JavaScript Object
A snippet of JavaScript to return the key of the highest value in an object
Michael Movsesov
Suppose you have the following JavaScript object and you need to find the key with the highest value - which is b in this case.
const numberObj = {
a: 1,
b: 50,
c: 12,
};Here's a quick function to help you do that. The solution is written in TypeScript, so if you are looking for a pure JS solution, just remove the types ๐.
function getMaxValueKey(obj: { [key: string]: number }): string {
return Object.keys(obj).reduce((a, b) => (obj[a] > obj[b] ? a : b));
}
getMaxValueKey(numberObj); // 'b'