Whale Talk - 6 times U & E instead of 2 time

Hello there,

Need your help to review my understanding of the concept.

Why did we get 6 times “U” & 6 times “E” in here:

let input = 'turpentine and turtles'
const vowels = ['a','i','u','e','o']
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])
    }
}
}
console.log(resultArray.join('').toUpperCase())

while we get 2 times “U” & 2 times “E” (as the project expected) in here:

let input = 'turpentine and turtles'
const vowels = ['a','i','u','e','o']
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])
    }
 }
}
}
console.log(resultArray.join('').toUpperCase())

Appreciate for the help.

1 Like

That’s because the last if statement, on the second case, the
if(input[i] === 'e' || input[i] === 'u'){...}
is enclosed by the anterior if statement, which is inside a for statement. That means that it will push the input[i] everytime for the anterior for statement, instead of pushing after the for loop.

1 Like

@mathsap To troubleshoot this type of problem it’s very useful to log i and j (and any other relevant variables) as well as your if statements themselves to see if your logic is working as you expect it to.

console.log(input[i] === 'e' || input[i] === 'u') for example…

It’s an incredibly useful approach that’s useful in other languages as well.

thanks for your help

1 Like

thanks for your suggestion

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.