1

This might be a basic question, however, I was struggling a little. So, what the code does is that it traverses an entire string passed to it and maps the occurrence of each letter. For instance, {P:28, A:15 ....}. What I wanted to know was that if I want to access the value, 28 in the case of P, and perform some sort of action on it, 28/(length of message) * 100, how can I do that and replace the value in the map. I would really appreciate it if someone can share it. Thanks.

P.S: I tried updating at every instance, but I need to only update once the for loop ends to get the correct percentage of occurrence.

const frequency = (message) => {
  message = message.toUpperCase().replace(/\s/g,'');

  for(let i = 0; i < message.length; i++)
  {
    let letter = message.charAt(i);
    if(map.has(letter)){
      map.set(letter, map.get(letter) + 1);
    }
    else{
      map.set(letter, (count));
    }
  }

  // const sortedMap = new Map([...map.entries()].sort());
  return map;
}
TanDev
  • 359
  • 3
  • 5
  • 13

2 Answers2

2

This is where the get function of the map will help you. If you know the key already (for e.g 'P').You can do this

let valueToChange  = map.get('P')
valueToChange+=1
map.set('P',valueToChange)

If you do not know the keys map.keys() will return the list of keys for you

Vikrant
  • 340
  • 1
  • 7
2

You do it the same way you did in your function. Call set. You can use for..of to iterate over all the values found in the map.

for([letter, count] of map) {
  map.set(letter, count/(length of message) * 100;
}
Spidy
  • 39,723
  • 15
  • 65
  • 83
  • Just a follow up tho. How can i sort the map according to the values? I know we can use map.entries() and sort() to sort according to the keys. – TanDev Sep 11 '20 at 14:41
  • https://stackoverflow.com/questions/37982476/how-to-sort-a-map-by-value-in-javascript – Spidy Sep 11 '20 at 21:15