Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Reversing the even length words of a string in JavaScript
We are required to write a JavaScript function that takes in a string and reverses the words in the string that have an even number of characters in them.
Let's say the following is our string:
const str = 'This is an example string';
We want to reverse the even length words of the above string i.e. reverse the following words:
This (4 characters) is (2 characters) an (2 characters) string (6 characters)
The word "example" has 7 characters (odd length), so it remains unchanged.
Syntax
function reverseEvenWords(str) {
return str.split(' ')
.map(word => word.length % 2 === 0 ? word.split('').reverse().join('') : word)
.join(' ');
}
Method 1: Using Array.reduce()
const str = 'This is an example string';
const isEven = str => !(str.length % 2);
const reverseEvenWords = (str = '') => {
const strArr = str.split(' ');
return strArr.reduce((acc, val) => {
if(isEven(val)){
acc.push(val.split('').reverse().join(''));
return acc;
};
acc.push(val);
return acc;
}, []).join(' ');
};
console.log(reverseEvenWords(str));
sihT si na example gnirts
Method 2: Using Array.map()
const str = 'This is an example string';
const reverseEvenWords = (str = '') => {
return str.split(' ')
.map(word => {
return word.length % 2 === 0
? word.split('').reverse().join('')
: word;
})
.join(' ');
};
console.log(reverseEvenWords(str));
sihT si na example gnirts
How It Works
The solution follows these steps:
-
Split the string into an array of words using
split(' ') -
Check each word's length using the modulo operator
% - Reverse even-length words by splitting into characters, reversing, and joining back
- Keep odd-length words unchanged
- Join the array back into a string with spaces
Comparison
| Method | Readability | Performance |
|---|---|---|
Array.reduce() |
More verbose | Good |
Array.map() |
Cleaner, more functional | Good |
Conclusion
Both methods effectively reverse even-length words in a string. The map() approach is more concise and functional, while reduce() offers more explicit control over the accumulation process.
Advertisements
