How else can I solve this?

How else can I solve this?
0

#1

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)


#2

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.


#3

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


#4

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.


#5

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.


#6

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.


#7

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


#8

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


#9

A couple of options without regular expression:

const countVowels = str => {
  const vowels = {a:1, e:1, i:1, o:1, u:1};
  let sum = 0;
  for (letter of str) {
    sum += +vowels[letter] || 0;
  }  
  return sum;
}

OR

const countVowels = str => {
  const vowels = {a:1, e:1, i:1, o:1, u:1};
  return [...str].reduce((count, letter) => count + (vowels[letter] || 0), 0);
};

#10

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.


#11

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


#12

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.


#13

I agree the regex solution is the best for this particular challenge. I just thought I would throw out another way to accomplish.