Get the Key of the highest Value in JavaScript object Given a hashmap (or a "Dictionary") as a JavaScript object, I'd like to get the Key who has the maximum Value - assuming all Values are integers.

In case there's more than one, I don't care which one of them.

Considering

var b = { '1': 9, '2': 7, '3': 7, '4': 9, '5': 3 };


I can extract the desired Key by:

parseInt(_(b).chain().pairs().max(function(p){return p[1];}).value()[0])


which returns 1.

How can this be achieved more elegantly?

I tried with _.invert as well but couldn't make it look better.
I don't know about elegant, but you can omit the initial _(), use + to convert to number instead of parseInt and just pull out the iterator.

var iterator = function(p){return p[1];}
var maxKey = +_.chain(b).pairs().max(iterator).value()[0];
// Removed the | 0 since the keys are integers to begin with


Here's an alternate way to do it using ES5 Array.prototype.reduce and Object.keys. You can also use underscore's _.reduce and _.keys for compatibility. Note that this runs through the entire array, so any duplicates found will use the latest value.

var max = Object.keys(b).reduce(function(max,key){
  return (max === undefined || b[key] &gt; b[max]) ? +key : max;
});


Making it more clear what we're doing, in case you aren't familiar of reduce, is to use Array.prototype.forEach (or _.each):

var max;
Object.keys(b).forEach(function(key){
  max = (b[key] &gt; b[max]) ? +key : max;
});