Getting key with the highest value from object

后端 未结 6 2041
闹比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: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'`

提交回复
热议问题