js reverse odd length words 1

js reverse odd length words

// Reverse the Odd Length Words
function reverseOdd(str) {
  return str.split(" ").map(w => w.length%2 ? [...w].reverse().join("") : w).join(" ");
}

console.log(reverseOdd("Bananas"));	// "sananaB"
console.log(reverseOdd("One two three four"));	// "enO owt eerht four"

Here is what the above code is Doing:
1. Split the string into an array of words
2. Map over the array of words
3. If the word’s length is odd, reverse the word
4. If the word’s length is even, leave the word as is
5. Join the array of words back into a string

Similar Posts