获取字典 nodej 中最大值的键



我想使用 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);

首先从对象中查找最大值,然后在Object.keys[b]上使用数组 find 方法并返回元素

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)

最新更新