Whale Talk - LOOPS / IF :(

URL - https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-loops/projects/whale-talk

The output should be IUUA, but I get IUUUUUUA, and I don’t know why haha. Can anyone spot the problem ?? E’s and U’s get repeated so I made an if statement that pushes E’s and U’s twice to my resultArray. The problem is that it pushes the U five times instead of one time when I use “Hi, Human” for my input. :frowning:

var input = "Hi, Human"
var vowels = ['a', 'e', 'i', 'o', 'u']
var resultArray = []
for (let i = 0; i < input.length; i++) {
  for (let j = 0; j < vowels.length; j++) {
    if (input[i] === vowels[j]) {
      resultArray.push(vowels[j])
    } if (input[i] === 'e' || input[i] === 'u') {
      resultArray.push(input[i])
    } 
  }
}

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

So for every letter in the input, it scans the vowel array to see if it matches. However, it also checks if input is an “e” or a “u” and adds it back on every time it is. Therefore when it reaches the u, it’ll add a “u” for every vowel in the array. You need this second if statement to only run when input[i] === vowels[j].

I still don’t get how to fix it bro.

var input = "Hi, Human";
var vowels = ['a', 'e', 'i', 'o', 'u'];
var resultArray = [];

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

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

    if (input[i] === vowels[j]) { //is the current letter of input a vowel?

      resultArray.push(vowels[j])  //yes, I'm storing it to resultArray

    };
    if (input[i] === 'e' || input[i] === 'u') {   //is it either the letter "e" or "u"?

      resultArray.push(input[i])  //yes, I'm storing either the letter "e" or "u" to resultArray

    } 
  } //move forward testing the current letter of input against the next vowel
}  //move forward testing the next letter of input against all the vowels

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

I added some comments to your code. If you notice you’re testing the second if whatever is the result of the first if. While you should test the second conditional only if the first conditional is true.
This is creating your bug.
Why?

  • Let’s say we have input[i] = “u”
  • Is input[i] the vowel “a”? No, move on
  • Is input[i] either “e” or “u”? Yes, store input[i] to result Array
  • Is input[i] the vowel “e”? No, move on
  • Is input[i] either “e” or “u”? Yes, store input[i] to result Array

  • Is input[i] the vowel “u”? Yes, store “u” to result Array
  • Is input[i] either “e” or “u”? Yes, store input[i] to result Array

Hope this helps and makes you smile :slight_smile:

2 Likes