Whale Project | Wrong Output

Hi,

I have been really struggling with this. Tried to look at the code other people have posted here (which is much shorter than mine because most people used the OR condition, but I really don’t understand the code although I have the right one now apparently: Why are the ‘e’ and the ‘u’ doubled when I use the same piece of code for the else statement.

const input = 'turpentine and turtles';

const vowels = ['o', 'i', 'e', 'a', 'u'];

let resultArray = [];

for (let inputIndex = 0; inputIndex < input.length; inputIndex++) {

 //console.log('inputIndex is ' + input[inputIndex]);

 for (let vowelsIndex = 0; vowelsIndex < vowels.length; vowelsIndex++) {

  //console.log(vowelsIndex);

    if (input[inputIndex] === vowels[vowelsIndex]) {

        if (input[inputIndex] === 'e') {

        resultArray.push(input[inputIndex])

        }

       if (input[inputIndex] === 'u') {

        resultArray.push(input[inputIndex])    

        } else {

        resultArray.push(input[inputIndex]);

   }

  }

 }

}

console.log(resultArray.join('').toUpperCase());

The push methods adds something additional to a string, so I understand the uu and ee, but why aren’t the other vowels double as well?
I hope I made myself clear. Would love some help here. Really want to get to the bottom of this.

Hi @sheisariver

Right now, your 'u’s aren’t doubled. Just the 'e’s are.
This is why:

if (input[inputIndex] === 'e') { 
        resultArray.push(input[inputIndex])  // e is pushed
}
if (input[inputIndex] === 'u') {
        resultArray.push(input[inputIndex])    
} else {
        resultArray.push(input[inputIndex]); // e is pushed a second time because the else is only valid for the second if clause

If you want to push all of the once, use else if instead. (But then you’d just need what’s inside the else.)
If you want to push 'e’s and 'u’s twice, delete the else and write:

if (input[inputIndex] === 'e') { 
        resultArray.push(input[inputIndex])  // e is pushed
}
if (input[inputIndex] === 'u') {
        resultArray.push(input[inputIndex])    // u is pushed
}
resultArray.push(input[inputIndex]); // all vowels are pushed, including 'e' and 'u'.
1 Like

Thank you, this is really helpful. It was a reminder to practice conditional statements again.

1 Like