Executing code after loop is finished (Pig Latin Challenge)

    function translatePigLatin(str) {
  var vowels = ["a","e","i","o","u"];
  var res;
  for (var i=0;i<vowels.length;i++) {
    if (str[0] !== vowels[i]) {
      res = str.slice(1,str.length) + str.slice(0,1) + "ay";
    }
    else {
      res = str + "way";
    }
    return res;
  }  
}

translatePigLatin("consonant");

How do i make “if” statement to execute the “res = str.slice…” part, after checking every vowel? Now it only check the first one, and then executes the code, and I want it to iterate through every letter in vowel array
Thanks for help :slight_smile:

You need to seperate your “checking” from your “replacing”. You are checking the first thing and then replacing right away. You could loop and have a boolean variable telling weather or not the first char matches any of the vowels, and then do the if statement.

But rather than doing the for loop, I think you might want to investigate the indexOf method for arrays.

Yes, this is exactly my question, how do i do the checking boolean var before if statement? I have no idea

edit: ok, i changed it to
if (str.indexOf(vowels[i]) >-1)
but “algorithm” word is not printing the right way again

ok, just did it:

function translatePigLatin(str) {
var vowels = [“a”,“e”,“i”,“o”,“u”];
var newArr = str.split("");
for (var i=0; i<vowels.length;i++) {
if (newArr[0] === vowels[i]) {
return newArr.join("") + “way”;
}
}
var firstLetter = newArr.shift();
newArr.push(firstLetter+“ay”);
return newArr.join("");
}
translatePigLatin(“california”);
but still dont know why “glove” should return “oveglay”