jeudi 17 juin 2021

Why does my array.map () doesn't work? Codewar: Stop gninnipS My sdroW

Here is the instruction of this codewars challenge:

Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed.

I tried two different ways to filter and get the 5-letter words reversed by using the I came across a challenge to figure out why I couldn't get the same output after I replace my ternary operator with the if-else statement. Here are the codes:

  1. Ternary Operator (this one works):

    function spinWords(words){ return words.split(' ').map(function (word) { return (word.length > 4) ? word.split('').reverse().join('') : word; }).join(' '); }

    console.log(spinWords("Hey fellow warriors"));

  2. if-else (However, this one doesn't reverse the 5-letter words as expected, need help! Have no idea the reason why this doesn't work.):

    function spinWords(string){
   
      
        return string.split('').map(function(word){
        
        
            if (word.length> 4){

                return word.split('').reverse('').join('');          
            
            }

            else {

                return word; 
            }

        }).join('');  
    }

   console.log(spinWords("Hey fellow warriors"));

Aucun commentaire:

Enregistrer un commentaire