Getting key with the highest value from object

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]);

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'`


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);

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

Tags:

Javascript