Whale Exercise - Nested For loop, with comparisons of Array and creation of a new one

link: [https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-loops/projects/whale-talk]

I need help. Why the following code is not working? the vowels of input should be inside the resultArray.

let input = 'frase para teste';
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];

for (let i = 0; i < input.lenght; i++) {
   for (let j = 0; j < vowels.lenght; j++) {
       if (input[i] === vowels[j]) {
          resultArray.push(input[i]);
           }
            if (input[i] === 'e' || input[i] === 'u') {
              resultArray.push(input[i]);
                }
           }
}
console.log(resultArray)

Hello @jhonathanc. Should

be length?

1 Like

Wow, thanks. English not my native language.

Now, please, why there are so many eee and aaa on my result? if I add a break, it just adds on e or a, and it should be two.

let input = 'turpentine and turtles';
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (let i = 0; i < input.length; i++) {
   for (let j = 0; j < vowels.length; j++) {
       if (input[i] === vowels[j]) {
         resultArray.push(input[i]);
          }
           if (input[i] === 'e' || input[i] === 'u') {
                resultArray.push(input[i]);
                break;
               }
    }
}
console.log(resultArray.join('').toUpperCase());

result: UEIEAUE

without the break the result is: UUUUUUEEEEEEIEEEEEEAUUUUUUEEEEEE

1 Like

The reason is that the break breaks this loop:

This iterates over this code:

5 times. The reason there are so many E and U is because of the closing } here:
Screen Shot 2020-05-31 at 11.28.10
This means that the if block here:

ends, so your checking to see if the input[i] === vowels[j] does not affect this code:

So, without the break, if the letter is an E or a U, it runs through this code 5 times. The break stops this from happening. If you want to have two Es or Us, then you would want to have a look at how you’ve nested your if statements.
I hope this helps!

1 Like