Skip to content
Advertisement

Get Max Key in Key-Value Pair in JavaScript

Please consider these Key-Value Pairs:

var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "1",
                    "100": "4",
                    "101": "0"}

I would like to get the highest value – in this example it would be 101.

How can I achieve this?

Thanks


Update 1:

I use this code: Fast way to get the min/max values among properties of object and Getting key with the highest value from object

but both return Max Value from string comparator

Advertisement

Answer

Try this.

You can iterate over the properties of the object and check for its value.

var dict_Numbers = {
  "96": "0",
  "97": "1",
  "98": "2",
  "99": "3",
  "100": "4",
  "101": "5"
};

var max = 0;

for (var property in dict_Numbers) {
  max = (max < parseFloat(property)) ? parseFloat(property) : max;
}

console.log(max);
7 People found this is helpful
Advertisement