Getting key with the highest value from object

后端 未结 6 2013
闹比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:16

    const data = {
      abc: '',
      myShortKey: '',
      myVeryLongKey: ''
    }
    
    
    const longestKeyLength = Math.max(...Object.keys(data).map((d) => d.length));
    
    console.log(longestKeyLength);
    
    console.log(Object.entries(data).map(([key, val]) => `${key}: ${key.length}`));

    0 讨论(0)
  • 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]);
    
    0 讨论(0)
  • 2020-11-27 03:19

    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

    0 讨论(0)
  • 2020-11-27 03:27

    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);
    
    0 讨论(0)
  • 2020-11-27 03:27

    Here is a suggestion in case you have many equal values and not only one maximum:

        const getMax = object => {
            return Object.keys(object).filter(x => {
                 return object[x] == Math.max.apply(null, 
                 Object.values(object));
           });
        };
    

    This returns an array, with the keys for all of them with the maximum value, in case there are some that have equal values. For example: if

    const obj = {apples: 1, bananas: 1, pears: 1 }
    //This will return ['apples', 'bananas', 'pears']

    If on the other hand there is a maximum:

    const obj = {apples: 1, bananas: 2, pears: 1 }; //This will return ['bananas']
    ---> To get the string out of the array: ['bananas'][0] //returns 'bananas'`

    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题