Reputation: 13487
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
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
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
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
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