Getting key with the highest value from object

后端 未结 6 2030
闹比i
闹比i 2020-11-27 02:51

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

6条回答
  •  -上瘾入骨i
    2020-11-27 03:38

    Very basic method. might be slow to process

    var v = {a: 1, b: 2, undefined: 1};
    
    function geth(o){
        var vals = [];    
        for(var i in o){
           vals.push(o[i]);
        }
    
        var max = Math.max.apply(null, vals);
    
         for(var i in o){
            if(o[i] == max){
                return i;
            }
        }
    }
    
    console.log(geth(v));
    

提交回复
热议问题