0

I have an object that contains some categories as keys and then an integer as a property:

{
    thing1: 12,
    thing2: 32,
    thing3: 9,
    thing4: 2
}

I need to find the mode out of all the numbers (the highest number - 32 in this case) and then return the key. What's the best way to do this?

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • 1
    Use `Object.keys()` to get a list of property names. Use `[].map()` to transform that into a list of values. Use `[].reduce()` to find the largest value. I hereby proclaim that to be the best way. – Pointy Mar 03 '15 at 19:58
  • Something like [that](http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value)? – kidA Mar 03 '15 at 20:07

1 Answers1

1

Here is one way I would go about it:

// Helper function to get values from an object
function values(obj) {
  return Object.keys(obj).reduce(function(result, nextVal) {
    result.push(obj[nextVal]);
    return result;
  }, []);
}

function getMode(obj) {
  var maxVal = Math.max.apply(Math, values(obj));
  var maxKey;

  Object.keys(obj).forEach(function(key) {
    if(obj[key] === maxVal) {
      maxKey = key;
    }
  });

  return maxKey;
}

Usage:

getMode(obj);
//=> "thing2"
istos
  • 2,654
  • 1
  • 17
  • 19