Skip to content
Advertisement

JavaScript counting the chars from one string but not a different string ones?

I am working on a function which is supposed to take a string as a parameter and return it as an object literal where the keys are each letter of the string and the values would be the number of times that letter appears in the string (Excluding whitespaces).

I have come up with a code that seems to work, however, it only seems to work on the first string I pass but not in the second one. I have provided two strings and their expected outcome in the below code:

JavaScript

If you run that code, you will see that the count is correct for the first string, however, for the second one it doesn’t count appropriately.

Advertisement

Answer

Whenever you hit a letter, you initialize the the value to 0, even if the letter existed before:

JavaScript

The inner loop is redundant. Just initialize/increment the current letter whenever you encounter it.

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement