How to return key of object with greater value in Javascript?

8

Let's say I have the following object:

var obj = {"frutas": 50, "vegetais": 100, "carnes": 150 };

How would I be able to return the key of the highest value item? Example:

obj.maxKey(); // "carnes"

I have tried some functions that treat arrays, but apparently they do not work with objects in the key: value pattern, for example:

Math.max.apply(null, meuArrayAqui);

So, how could I return the key of the highest value item ?

    
asked by anonymous 16.03.2015 / 20:57

3 answers

6

There is no native function for this, so you will have to check all the values to find the largest:

var obj = {"frutas": 50, "vegetais": 100, "carnes": 150 };
var maior = -Infinity;
var chave;
for(var prop in obj) {
    // ignorar propriedades herdadas
    if(obj.hasOwnProperty(prop)) { 
         if(obj[prop] > maior) {
             maior = obj[prop];
             chave = prop;
         }
    }
}
alert(chave);

The principle is this. Of course, for real use it is best to wrap this in a function. Depending on the usage you want, you can still make some optimizations.

    
16.03.2015 / 21:25
3

The simplest way seems to be with a loop, but if you look for a more functional alternative, this can be done as follows:

  • Get all the keys of the object, using Object.keys ;
  • Sort them in descending order of value (you need to use a custom function for this);
  • Get the first element.

Example:

var obj = {"frutas": 50, "vegetais": 100, "carnes": 150 };

var maior = Object.keys(obj).sort(function(a,b) {
                return obj[a] > obj[b] ? -1 :
                       obj[b] > obj[a] ? 1 : 0;
            })[0];

document.querySelector("body").innerHTML += "<p>" + maior + "</p>";
    
16.03.2015 / 21:36
2

Using each of jQuery and traversing all objects, you can do this:

function getKeyOfMaxObjValue(obj){
  // Variável que armazenará a maior key.
  var key;
  // Variável auxiliar para checar os valores
  var value = 0;
  $.each(obj, function(idx, val){
    // Se o valor atual da iteração é maior que o auxiliar
    if(val > value){
      // Atualiza o valor da variável auxiliar
      value = val;
      // Atribue a nova key
      key = idx;
    }
  });
  return key;
}
    
16.03.2015 / 21:23