Home > Enterprise >  JavaScript Trying to Print The Number of Times a Letter Appears In String But It Prints More than On
JavaScript Trying to Print The Number of Times a Letter Appears In String But It Prints More than On

Time:07-15

In the code below, I am trying to check how many times a letter in a string appears. Problem with the code below is that it prints each letter more than once. It needs to collect all the same letters and show the number of times it occurs in the string.

const string = 'mississippi'

const letters = [...string]

let currentLetter = ''
let letterOccurance = []


for(let i = 0; i < letters.length; i  ){
  let letterFrequency = letters.filter((letter)=>{
    return letter === letters[i]
  })

  letterOccurance.push([`${letters[i]}`,letterFrequency.length])
}

console.log(letterOccurance)

CodePudding user response:

You're always pushing the letter to the array, whether it already exists there or not:

letterOccurance.push([`${letters[i]}`,letterFrequency.length])

You could check if it exists first:

if (!letterOccurance.find(l => l[0] === letters[i])) {
  letterOccurance.push([`${letters[i]}`,letterFrequency.length])
}

Or even skip it entirely if you've already seen it, since the first time you find any letter you already know its complete count:

for(let i = 0; i < letters.length; i  ){
  if (letterOccurance.find(l => l[0] === letters[i])) {
    continue;
  }
  // the rest of the loop...
}

There's honestly a variety of ways you could step back and re-approach the problem. But for the question about why letters are repeating, that's simply because each iteration of the loop unconditionally appends the letter to the resulting array.

CodePudding user response:

That's too much code just to get the number of times a letter appears in a string. Try the following code:

const string = 'mississippi';

let frequency = {};

for (let letter of string) {
  if (frequency[letter]) {
    frequency[letter]  ;
  } else {
    frequency[letter] = 1;
  }
}

console.log(frequency);

  • Related