Clean Markup

Reverse words algorithm in Javascript

Reverse words algorithm in Javascript

The reverse words algorithm is pretty easy and straight forward to implement, it will improve your critical thinking skills, the idea is to reverse each word in a given sentence but keep in mind on every word in the string should be reversed but the string as a whole should not be reversed.

So for example if, we pass in the string "This is a string of words" the result should be this "Siht si a gnirts"

Input : Sentence
Output : Reversed words of the exact sentence.

Implementation #

function reversedWord(str) {
var wordsArray = str.split(" ");
var resultArray = [];
wordsArray.forEach((word) => {
var charArray = word.split("");
var rWord = "";
charArray.forEach((char) => {
rWord = char + rWord;
});
resultArray.push(rWord);
});
return resultArray.join(" ");
}

Main Point: Critical thinking skills.

The code is availalbe here : https://repl.it/@ahmd1/Reversed-Word

Credits #

Photo by Hugo Sousa

← Home