DooDoo
DooDoo

Reputation: 13487

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

Upvotes: 9

Views: 16763

Answers (5)

mplungjan
mplungjan

Reputation: 178422

Applying to the keys the easily found Getting key with the highest value from object paying attention to the strings

const dict_Numbers = {
    "96": "0",
    "97": "1",
    "08": "8", // just to make sure
    "09": "9", // just to make sure
    "98": "2",
    "99": "3",
    "100": "4",
    "101": "5"
  },
  max = Object.keys(dict_Numbers)
  .reduce((a, b) => +a > +b ? +a : +b)
console.log(max)

But as I commented on the question, there is a neater way using Math.max on the Object.keys

Now even more elegant using spread

const dict_Numbers = {
    "96": "0",
    "97": "1",
    "08": "8", // just to make sure
    "09": "9", // just to make sure
    "98": "2",
    "99": "3",
    "100": "4",
    "101": "5"
  },
  max = Math.max(...Object.keys(dict_Numbers))
console.log(max)

Upvotes: 9

Deep
Deep

Reputation: 9804

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

Upvotes: 1

str
str

Reputation: 45029

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

console.log(Math.max(...Object.keys(dict_Numbers)));

Note that this code uses ES6 features.

Upvotes: 4

Aditya Singh
Aditya Singh

Reputation: 116

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

for (key in dict_Numbers) {
  intKey = parseInt(key);
  if (intKey > maxKey) {
    maxKey = intKey;
  }
}
console.log(maxKey);

Upvotes: 0

sinisake
sinisake

Reputation: 11338

Nice example from MDN:

var dict_Numbers = {"96": "0",
                    "97": "1",
                    "98": "2",
                    "99": "3",
                    "100": "4",
                    "101": "5"}
                    
                    
function getMax(obj) {
  return Math.max.apply(null,Object.keys(obj));
}
console.log(getMax(dict_Numbers));

Upvotes: 14

Related Questions