javascript - 获取字典nodejs中最大值的键
问题描述
我想使用nodejs在字典中获取最大值的键。这就是我所做的,但它返回最大值而不是键。
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]
您可能只想使用键/值对来简化这一点。或者更基本的方法:
let maxKey, maxValue = 0;
for(const [key, value] of Object.entries(b)) {
if(value > max) {
maxValue = value;
maxKey = key;
}
}
console.log(index);