How else can I solve this?

It’s counting vowels in a string and here is how I solved it:

function countVowels(str) {
    let result = 0;
    let vowels = "aeiou"
    
    for (let i = 0; i < str.length; i++) {
        for (let j = 0; j < vowels.length; j++) {
            if (str[i] === vowels[j]) {
                result++;
                }
            }
        }
    return result;
};

What is the way to do it without using a second for loop? I tried indexOf but couldn’t figure it out. Things like if (str.indexOf(vowels) === -1)

Instead of iterating through vowels each time, you could just hard code your comparisons manually.
Alternatively, you could try using Regular Expressions, which would eliminate the need for the for loops entirely.

Can you show me how you’d go about that?

Something like this:

function countVowels(str) {
    let result = 0;
    
    for (let i = 0; i < str.length; i++) {
        let character = str[i];
		switch(character){
			case a:
			case e:
			case i:
			case o:
			case u:
				result++;
				break;
		}
	}
    return result;
};

Haven’t tested it, but I’m sure this would work.

Programming is so so so humbling, it’s crazy. Didn’t even think of a switch statement here. You can solve everything in numerous ways.

You could also use the regex approach, simply remove everything that isn’t a vowel and return the string length:

let countVowels = (str) =>  str.replace(/[^aeiou]/gi, "").length;


console.log(countVowels( "four" ) )

As zapcannon99 pointed out, the AEIOU is redundant with the i flag, thus I’ve removed it. sigh.

1 Like

Though you wouldn’t need the AEIOU if you have the “i” flag I think.

true that. I’m a suspenders and belt man. and I haven’t had enough coffee. :wink:

1 Like

I like that second one. I don’t think that would have been my first thought, but it really makes sense. Still like me my regex though. And for me, I find I really need to practice with regular expressions, they tend to get muddy in my brain.

How can I trust a man if he can’t even trust his own pants?!

who said anything about pants??! Just suspenders. and a belt. Need the belt to clip the suspenders to. No mention of pants. Beware your assumptions.

… sorry, that got WAY off topic.

1 Like