Reverse only the odd length words - JavaScript


We are required to write a JavaScript function that takes in a string and reverses the words in the string that have an odd number of characters in them.

Any substring in the string qualifies to be a word, if either it is encapsulated by two spaces on either ends or present at the end or beginning and followed or preceded by a space.

Let’s say the following is our string −

const str = 'hello beautiful people';

The odd length words are −

hello
beautiful

Example

Let us write the code for this function.

const str = 'hello beautiful people';
const idOdd = str => str.length % 2 === 1;
const reverseOddWords = (str = '') => {
   const strArr = str.split(' ');
   return strArr.reduce((acc, val) => {
      if(idOdd(val)){
         acc.push(val.split('').reverse().join(''));
      return acc;
   };
   acc.push(val);
   return acc;
   }, []).join(' ');
};
console.log(reverseOddWords(str));

Output

Following is the output in the console −

olleh lufituaeb people

Updated on: 16-Sep-2020

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements