get key of max value in dictionary nodejs

痞子三分冷 提交于 2020-12-26 04:05:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!