Getting key with the highest value from object

后端 未结 6 2034
闹比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条回答
  •  再見小時候
    2020-11-27 03:18

    Supposing you've an Object like this:

    var obj = {a: 1, b: 2, undefined: 1}
    

    You can do this

    var max = Math.max.apply(null,Object.keys(obj).map(function(x){ return obj[x] }));
    console.log(Object.keys(obj).filter(function(x){ return obj[x] == max; })[0]);
    

提交回复
热议问题