Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting key with the highest value from object

Tags:

javascript

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).

like image 513
Tomek Buszewski Avatar asked Dec 09 '14 10:12

Tomek Buszewski


People also ask

How do you find the key of an object with its value?

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.

How do I return a key to the highest value in Python?

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.

How do I find the index of an object in a key?

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] .


2 Answers

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); 
like image 59
CD.. Avatar answered Sep 20 '22 18:09

CD..


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

like image 23
Faris Zacina Avatar answered Sep 23 '22 18:09

Faris Zacina