Curly
Curly

Reputation: 109

JS: What is the cleanest way of finding the highest value from an object and return its key?

I am trying to iterate through some characters and using a hashmap to keep track of characters seen already. I now have an object with characters and how many times they are encountered. I know I can get the values by doing:

Object.value(myObj).sort((a,b) => {return b - a})[0] but I don't know how to use that highest value I have to relate back to the key it belongs to.

Upvotes: 1

Views: 61

Answers (3)

ellipsis
ellipsis

Reputation: 12152

It will take the highest value and compare the keys. After that it will return the key associated with the highest value.

var a={w:1,e:2,g:5};
var value=Object.values(a).sort((a,b) => {return b - a})[0];
console.log(Object.keys(a).filter((e)=>a[e]==value?true:false)[0])

Upvotes: 0

Evert
Evert

Reputation: 99533

let maxValue;
let maxKey;

for (const [key, value] of Object.entries(myObj)) {

  if (value > maxValue) {
    maxValue = value;
    maxKey = key;
  }

}

Upvotes: 2

Amadan
Amadan

Reputation: 198314

If you want the key of the highest value, sort the keys:

Object.keys(myObj).sort((a,b) => {return myObj[b] - myObj[a]})[0]

EDIT: This is the minimal modification of your code; though a straight search as per Evert's answer will be faster, if you don't need the other elements.

Upvotes: 1

Related Questions