最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get key of max value in dictionary nodejs - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3
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 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)

发布评论

评论列表(0)

  1. 暂无评论