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.
b['1']
andb['4']
. You say you want the "first" key ('1'
), but JS objects are technically unordered, so you could get the'4'
key instead. So do you want the lowest key with the highest value, or simply any key with the highest value? \$\endgroup\$parseInt
, you should always specify a base:parseInt(…, 10)
. \$\endgroup\$