获取字典nodejs中最大值的键 [英] get key of max value in dictionary nodejs
本文介绍了获取字典nodejs中最大值的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用nodejs在字典中获取最大值的键.这是我所做的,但是它返回最大值而不是键.
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);
有什么想法吗?
推荐答案
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);
这篇关于获取字典nodejs中最大值的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文