Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check how many times character from string appears?

I want to count how many times each letter from params appears in this string. What am I doing wrong?

function solution(word) {
    let temp = {}
    for(const c of word) {
      temp[c]++;
      console.log(temp[c])
  }
  
}

solution("PAPAYA")

It should output me numbers below for each letter, but i keep getting NaN

1 // P appeared once
1 // A appeared once
2 // P appeared second time
2 // A appeaed second time
1 // Y Once
3 // A appeared third time

so it should look like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  A: 3,
  P: 2,
  Y: 1
}

>Solution :

Here is an easy solution without changing your code to much

function solution(word) {
    let temp = {}
    for(const c of word) {
      if (temp[c] === undefined)
        temp[c] = 1;
       else temp[c]++;
  }
  console.log(temp)
}

solution("PAPAYA")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading