问题
I want to get the key of the max value in a dictionary using nodejs. This is what I have done but it returns the max value not the key.
var b = { '1': 0.02, '2': 0.87, '3': 0.54, '4': 0.09, '5': 0.74 };
var arr = Object.keys( b ).map(function ( key ) { return b[key]; });
var max = Math.max.apply( null, arr );
console.log(max);
Any idea how to do it?
回答1:
const result = Object.entries(b).reduce((a, b) => a[1] > b[1] ? a : b)[0]
You might just wanna work with key/value pairs to simplify this. Or a more basic approach:
let index, max = 0;
for(const [key, value] of Object.entries(b)) {
if(value > max) {
max = value;
index = key;
}
}
console.log(index);
回答2:
First find the highest values from the object, then use array find method on Object.keys[b]
& return the the element
var b = {
'1': 0.02,
'2': 0.87,
'3': 0.54,
'4': 0.09,
'5': 0.74
};
var highestVal = Math.max.apply(null, Object.values(b)),
val = Object.keys(b).find(function(a) {
return b[a] === highestVal;
});
console.log(val)
来源:https://stackoverflow.com/questions/50723396/get-key-of-max-value-in-dictionary-nodejs