JavaScript Exercises Basic#10 - Counting specific alphabet from the string

JavaScript Exercises Basic#10 - Counting specific alphabet from the string

You will be given a string and a random alphabet. Write a program which returns how many of the alphabet has been used in the string.

Result Example

Screenshot 2022-04-20 at 16.55.34.png Solution

  1. Declare a variable called 'answer' to store the count and initiate it with 0.
  2. Use for...of loop to iterate through the string and compare all of the letters with the given alphabet. If they match, increment the count.
  3. Return 'answer'.
function solution(str, key){
               let answer = 0;
               for (let x of str){
                    if (x === key) answer++;
               }

               return answer;
           }