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 (5 characters - odd)
beautiful (9 characters - odd)

Note that "people" has 6 characters (even), so it won't be reversed.

Solution

Let us write the code for this function:

const str = 'hello beautiful people';

const isOdd = str => str.length % 2 === 1;

const reverseOddWords = (str = '') => {
    const strArr = str.split(' ');
    return strArr.reduce((acc, val) => {
        if(isOdd(val)){
            acc.push(val.split('').reverse().join(''));
            return acc;
        }
        acc.push(val);
        return acc;
    }, []).join(' ');
};

console.log(reverseOddWords(str));

Output

olleh lufituaeb people

How It Works

The function works by:

  1. Split the string: str.split(' ') creates an array of words
  2. Check each word: The isOdd helper function checks if word length is odd
  3. Reverse odd words: For odd-length words, split into characters, reverse, and rejoin
  4. Keep even words unchanged: Even-length words are added as-is
  5. Join back: All words are joined back with spaces

Alternative Approach Using map()

const reverseOddWordsMap = (str = '') => {
    return str.split(' ').map(word => {
        return word.length % 2 === 1 
            ? word.split('').reverse().join('') 
            : word;
    }).join(' ');
};

console.log(reverseOddWordsMap('hello beautiful people'));
console.log(reverseOddWordsMap('the quick brown fox'));

Output

olleh lufituaeb people
eht kciuq nworb fox

Conclusion

This function efficiently identifies odd-length words and reverses only those, leaving even-length words unchanged. The map() approach provides a cleaner, more functional programming style.

Updated on: 2026-03-15T23:18:59+05:30

569 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements