admin管理员组文章数量:1356424
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?
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?
Share Improve this question asked Jun 6, 2018 at 14:51 isanmaisanma 1752 gold badges2 silver badges14 bronze badges 4-
return b[key]
->return key
– Keith Commented Jun 6, 2018 at 14:52 - That returns the highest key not the key of the max value – isanma Commented Jun 6, 2018 at 14:53
- Use Object entries, it will give you both the key & value. – Keith Commented Jun 6, 2018 at 14:54
- It's not a dictionary, it's an object. – T.J. Crowder Commented Jun 6, 2018 at 15:24
2 Answers
Reset to default 3const 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 maxKey, maxValue = 0;
for(const [key, value] of Object.entries(b)) {
if(value > max) {
maxValue = value;
maxKey = key;
}
}
console.log(index);
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)
本文标签: javascriptget key of max value in dictionary nodejsStack Overflow
版权声明:本文标题:javascript - get key of max value in dictionary nodejs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744059374a2583843.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论