120

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) from it? I tried converting it to array and then sorting, but it didn't work out, since it got sorted alphabetically (and it seems like a overkill to juggle data back and forth just for getting one value out of three).

3

9 Answers 9

193

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);
7
  • 2
    Thanks, but please note that there can be more items, like c, d, e... x. Dec 9, 2014 at 10:18
  • 16
    this works for more items.. the reduce function is an iteration through the whole array ;) Dec 9, 2014 at 10:19
  • Sorry for being a bother, but how can I also get a 2 besides b? Dec 9, 2014 at 10:43
  • @CD.. if I use this in this case "var obj = {a: 1, b: 2, c: 2};" it return only c but I need b & c, means all keys with highest values
    – Dinesh
    Mar 13, 2016 at 7:48
  • 4
    @Dinesh, try: var obj = {a: 1, b: 2, c: 2}, keys = Object.keys(obj), largest = Math.max.apply(null, keys.map(x => obj[x])) result = keys.reduce((result, key) => { if (obj[key] === largest){ result.push(key); } return result; }, []);
    – CD..
    Mar 13, 2016 at 7:55
39

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

1
  • 21
    As of Lo-Dash 4.0.0 this should now be var maxKey = _.maxBy(_.keys(obj), function (o) { return obj[o]; });.
    – thodic
    Mar 29, 2017 at 11:45
13

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

2
  • Hi, where should I put the object var exactly? When I console.log I get a "function getMax()"
    – Jeff
    Oct 25, 2018 at 10:31
  • 1
    object is the argument that the function above takes, the above is the ES6 syntax for defining functions, equivalent to: function getMax(object) , does that answer your question?
    – polyccon
    Oct 25, 2018 at 12:31
10
{a: 1, b: 2, undefined: 1}

The best work around I've seen is this

const chars = {a: 1, b: 2, undefined: 1}

//set maximum value to 0 and maxKey to an empty string
let max = 0;
let maxKey = "";

for(let char in chars){
  if(chars[char]> max){
    max = chars[char];
    maxKey= char
  }
}

console.log(maxKey)

8

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

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

Combination of some ideas from other answers. This will get all the keys with the highest value, but using the spread operator to get the maximum value and then filter array method:

const getMax = object => {
  let max = Math.max(...Object.values(object))
  return Object.keys(object).filter(key => object[key]==max)
}

let obj = {a: 12, b: 11, c: 12};
getMax(obj)
1

If you need to return an array from an object with the keys for all duplicate properties with the (same or equal) highest value, try this:

const getMax = Object.keys(object)
   .filter(x => {
             return object[x] == Math.max.apply(null, 
             Object.values(object));
   })
var object = { orange: 3, blue: 3, green: 1}
console.log(getMax) // ['orange', 'blue']
1
  • This helps a lot for this scenario. Though, running this in the console does produce an error for me. The fix is to simply declare the object first so that the references resolve.
    – ONMNZ
    Nov 2 at 20:35
0
let data = {a:1,b:2,undefined:3}
let maxValue = Object.entries(data).sort((x,y)=>y[1]-x[1])[0]

note: this is a very expensive process and would block the event loop if used with objects of large sizes(>=1000000). with large array slice the entries and call the above method recurrently using setTimeout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.