 Open in App
Not now

# How to get the number of occurrences of each letter in specified string in JavaScript ?

• Difficulty Level : Easy
• Last Updated : 06 Jan, 2023

In this article, we are given a string, our task is to find the occurrence of a character in the string with the help of a user-defined function.

```Example:
Input : "hello"
Output : h occur 1 times
e occur 1 times
l occur 2 times
o occur 1 times
Explanation : here "hello" have 1 h, so it have 1 value.
as same e have 1, l have 2 , o have 1.
Example 2:
Input : "did"
Output: d occur 2 times
i occur 1 times```

Approach 1: In this approach, we use a map data structure to store the number of times characters occur.

• First, we initialize the map with a key for each character of the string, and the value for each is 0.
• We iterate over the string and increment the value of the character.
• Finally, print key-values of the map.

Example: This example shows the use of the above-explained approach.

## Javascript

 ``

Output:

```h  occurs  1 times
e  occurs  1 times
l  occurs  3 times
o  occurs  2 times
w  occurs  1 times
r  occurs  1 times
d  occurs  1 times```

Approach 2: In this approach, we use nested for loop to iterate over the string and count for each character in the string.

• First, initialize count with value 0 for the ith value of the string.
• Now we iterate over the string if ith value matches with the character, increasing the count value by 1.
• Finally, print the value of the count.

Example: This example shows the use of the above-explained approach.

## Javascript

 ``

Output:

```g occurs 2 times
f occurs 1 times
h occurs 1 times
e occurs 1 times
l occurs 2 times
o occurs 1 times```

Approach-3: In this approach, we will use the for loop in order to iterate over the complete string itself. This is the simplest approach we may implement in order to find out the resulting task.

• We will initialize a count variable which will store the count of each and every character in a string.
• Then using a for loop we will check how many times a character in the string has occurred or repeated or is present.

Example: This example shows the use of the above-explained approach.

## Javascript

 ``

Output:

```h occur 1 times
e occur 1 times
l occur 2 times
o occur 1 times```

My Personal Notes arrow_drop_up
Related Articles