Get Max Key in Key-Value Pair in javascript
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)