Skip to content Skip to sidebar Skip to footer

Get Key Of Max Value In Dictionary 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,

Solution 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 maxKey, maxValue = 0;

for(const [key, value] ofObject.entries(b)) {
  if(value > max) {
    maxValue = value;
    maxKey = key;
  }
}

console.log(index);

Solution 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)

Post a Comment for "Get Key Of Max Value In Dictionary Nodejs"