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
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.
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));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With