Search code examples
javascriptarraysstringsortingstring-concatenation

How to Save Item of The Indexed Array That Had Been Changed Into String Into Variable Javascript


May I ask my first question. Sorry if the title is so bad. It was a bit annoy me. So I was build a function to reverse a string that have 5 character or more like this.

function spinWords(str) {
    str2 = str.split(" ");
    str3 = [];
      
    for (i = 0; i < str2.length; i++) {
       str3 = str2[i].split("");
       if (str3.length >= 5) {
          str3.reverse();
       }
       str4 = str3.join("");
       return str4;
    }
}
spinWords("Welcome To The Club");`

The output that I expected is like this

emocleW To The Club

But that code output is this

emocleW
To
The
Club

Is there any solution, at least to combine the four iteration string into one line?

Every help would be very nice. Thanks!!!


Solution

  • function spinWords(str) {
    
      function reverseString(str) {
        return str.split("").reverse().join(""); 
      }
    
      const words = str.split(" ");
      const spinnedWords = words.map(word => {
        if (word.length >=5 ) return reverseString(word);
        else return word;
      });
    
      return spinnedWords.join(' ');
    }
    
    spinWords("Welcome To The Club");