Why won't this iterate?

Viewed 42

I am trying to make this Pig Latin function (I just started coding 3 weeks ago, so go easy on me), and I can't figure out why I can't get the array made from .split(' ') and then iterated through to join back again. In the output I only get the first word. The code is below:

function pigLatin(str) {
  let str1 = str.split(' ')
  for (let i = 0; i < str1.length; i++) {
    if (str1[i].length <= 1) {
      return str1[i]; 
    }
    else {
      let first = str1[i].substring(0,1);
      let word = str1[i].substring(1);
      str = word + first + 'ay';
      return str
    }
  }
}

console.log(pigLatin("This is a test"));

Keep in mind that I was considering adding regex and more else if statements, but I can't even get this to work yet. Any help is greatly appreciated.

1 Answers

You're returning too early. You should be adding each word to an array, and at the end of your loop you should concatenate the words in the array to form a new string which you should return. See my comments for how I altered your code:

function pigLatin(str) {
let r = [] // The array to build
let str1 = str.split(' ')
for (let i = 0; i < str1.length; i++) {
  if (str1[i].length <= 1) {
    r.push( str1[i] );  // Add to end of array
  }
  else {
    let first = str1[i].substring(0,1);
    let word = str1[i].substring(1);
    str = word + first + 'ay';
    r.push(str) // Add to end of array
    }
  }
  return r.join(' ') // Join strings in array and return new string
}

console.log(pigLatin("This is a test"));

Related