I have a object like that one:
Object {a: 1, b: 2, undefined: 1}
How can I quickly pull the largest value identifier (here: b
) from it? I tried converting it to array and then sorting, but it didn't work out, since it got sorted alphabetically (and it seems like a overkill to juggle data back and forth just for getting one value out of three).
To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.
Python find highest value in dictionary By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict. get() method is used.
To get an object's key by index, call the Object. keys() method to get an array of the objects keys and use bracket notation to access the key at the specific index, e.g. Object. keys(obj)[1] .
For example:
var obj = {a: 1, b: 2, undefined: 1}; Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
In ES6:
var obj = {a: 1, b: 2, undefined: 1}; Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
Using Underscore or Lo-Dash:
var maxKey = _.max(Object.keys(obj), function (o) { return obj[o]; });
With ES6 Arrow Functions:
var maxKey = _.max(Object.keys(obj), o => obj[o]);
jsFiddle demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With