Superflous comma with str.push() in pig latin algorithm

I’m working on the Pig Latin algorithm and almost have it cracked but there’s a weird comma appearing on the ‘glove’ test case. It seems to be getting put there during the str.push(), but using str.join(’,’) doesn’t seem to get rid of it… Any insights?

// Pig latin translator
// Move first consonant cluster to the end, suffix -ay
// Suffix -way if vowel initial
function translatePigLatin(str) {
  var vowels = ['a', 'e', 'i', 'o', 'u'];
  str = str.split('');
  var indices = [];
  var fV = '';

  // If it starts with a vowel
  if (vowels.includes(str[0])) {
    console.log('Starts with a vowel');
    return str.join('') + 'way';
  } else {
    // If it doesn't start with a vowel
    for (letter in vowels) {
      if (str.indexOf(vowels[letter]) != -1) {
        // Get the indices of the vowels
        indices.push(str.indexOf(vowels[letter]));
        fV = Math.min(...indices);
      }
    }
  } 

  str.push(str.slice(0, fV));
  str.splice(0, fV);

  return str.join('')+'ay'; // Outputting 'oveg,lay'
}

translatePigLatin('glove'); // 'oveglay'

Try running it through the debugger with devtools (e.g. by adding debugger; before the function call at the end).

In this line: str.push(str.slice(0, fV));, you are pushing an array onto the existing array. So the last element of str ends up being an array ([‘g’, ‘l’]).

When you join the array a couple of lines later, that inner array gets converted to a string, adding a comma between the latters in the process. Since you are using array destructuring earlier in the code, you could use it again to make sure you are pushing the individual letters rather than an array of letters.

1 Like

here is another solution if you like

function translatePigLatin(str) {
  
  let loop= str.split(/(?=[aeiou])/);
    return /^[aeiou]/.test(str)==true?str.concat("way"):str.slice(loop[0].length).concat(loop[0]+"ay");
 }
translatePigLatin("Consonant");