Our challenge today is called return the number of vowels in a given string, we will create a function that will take a string as an argument, within the body of the function we will write code that will count the number of vowels we have in the string we passed in as an argument



For this challenge we will have two solutions, the first one will return every vowel in a string. What I am trying to say is if we have a string "keep coding", our function will count the letter "e" twice, our function will return to us that we have 4 vowels.

The second solution will count one vowel once, so in the case of "keep coding", our function will return to us that we have 3 vowels because it can not count the letter "e " twice since its the same letter.

Please complete the challenges first before checking out my solution

Here is the first solution

const vowels = ["a", "e", "i", "o", "u"]

const countVowels = (str)=>{
    let results = 0;

    for(let index = 0; index < str.length; index++){
        if(vowels.indexOf(str[index]) >= 0){
            results+=1
        }
    }

    return results
}

console.log(countVowels("web developer"));

// output = 5


Like I have explained above that the first solution will return incorrect values, because we do not have 5 vowels there but instead we have 2.

Let us dive in to the second solution which will give us the more accurate number of the vowels in the string

const vowels = ["a", "e", "i", "o", "u"]

const countVowels = (str)=>{
    const vowelsArray = []

    const oneVowel = str.split("")

    for(let index = 0; index < oneVowel.length ; index++){

        if(vowels.indexOf(oneVowel[index]) >= 0 && 
           vowelsArray.indexOf(oneVowel[index]) == -1){
            vowelsArray.push(oneVowel[index])
        }
    }

    return vowelsArray.length
}

console.log(countVowels("web developer"));

// output = 2

Sometimes the first solution might be the way to count the vowels because some challenges actually want you to count every vowel, but if you want to return the more accurate number of vowels by not counting the same letter twice then the second solution is the way to go