Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Max Key in Key-Value Pair in JavaScript

Tags:

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

like image 640
Arian Avatar asked Dec 28 '16 08:12

Arian


People also ask

Can we get key from value in JavaScript?

To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.


2 Answers

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));
like image 142
sinisake Avatar answered Sep 18 '22 16:09

sinisake


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)
like image 44
mplungjan Avatar answered Sep 18 '22 16:09

mplungjan