Juan Juan - 26 days ago 5
Javascript Question

Join() methods only transforme some arrays into string

Im trying to make a code to add the string "way" to the words that begin with a vowel, or add the word "ay" and the first letter of the word at the end of the string if the word begin with a consonant. I splited the words to see if the start with a consonant or a vowel , then add the "way" or "ay" with the first leter, and at last joined the array to show the resultant string. The problem is that the join only worked for the words that begin with vowel. How can i fix this?

the code:

function isVowel(c) {
return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1;
}

function translatePigLatin(str) {

str=str.split('');
var firstLetter=str[0];

if(isVowel(firstLetter)) str.push("way");

else {

str.splice(0,1);
str=str+firstLetter+"ay";

}

str= Array.prototype.join.call(str,"");
alert(str);

return str;
}

translatePigLatin("consonant");

Answer

You were adding with operator + to the array which can mess up the type, casting the array to a string. You should use push on an array to get the behaviour you seek.

function isVowel(c) {
  return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1;
}

function translatePigLatin(str) {

  str=str.split('');
  var firstLetter=str[0];

  if(isVowel(firstLetter)){
   
    str.push("way");

  }else {    

     str.splice(0,1);
     str.push(firstLetter+"ay");

  }

  str= Array.prototype.join.call(str,"");
  alert(str);

  return str;
}

translatePigLatin("consonant");