1

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.

Curly
  • 99
  • 5
  • 1
    Can you show your object in your question? – Van Tho Jan 28 '19 at 04:35
  • Possible duplicate of [Getting key with the highest value from object](https://stackoverflow.com/questions/27376295/getting-key-with-the-highest-value-from-object) – smac89 Jan 28 '19 at 04:51

3 Answers3

2
let maxValue;
let maxKey;

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

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

}
Evert
  • 93,428
  • 18
  • 118
  • 189
  • 1
    This is much more efficient than grabbing all of the keys and then sorting them, as it takes only 1 iteration and uses less RAM as it doesn’t make extra arrays. – Nate Jan 28 '19 at 05:37
1

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I feel the operator should be greater than instead of minus – vdj4y Jan 28 '19 at 04:42
  • @vdj4y: First of all, I left the operator alone - I was going for minimal modification of OP's code. Secondly, the operator is correct if the sorted values are numeric, as the callback for `sort` needs to return an integer, not a boolean. For any other kind of comparison (e.g. strings), this is indeed not correct - but then OP's code wouldn't have worked either. In such a case, a conditional should be made so it can return `-1`, `0` or `1`; not just plain `true` or `false`. – Amadan Jan 28 '19 at 04:45
  • yeah, it return integer, 1 or 0 or -1. I could be wrong, but from what I know. it's like "if(a < b) return 1 else if (a ==b) return 0 else return -1". – vdj4y Jan 28 '19 at 04:47
  • @vdj4y: The spec just says the three cases are negative, zero and positive; with `31 - 47` you get a negative, which is good enough, no need to transform it into `-1`. With strings you can't do that with just subtraction, and we return `-1` for convention and simplicity, even though `-16` would work just as well. – Amadan Jan 28 '19 at 04:49
0

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])
ellipsis
  • 12,049
  • 2
  • 17
  • 33