How do I achieve the desired output by passing the specified string as an argument to a function?
input:
"Reverse this line"
output:
"esreveR siht enil"
This is my implementation
function reverseWords(string) {
var wordArray = string.split(" ");
var resultWordArray = [];
var finalSentence;
wordArray.forEach(word => {
if (word == " ") {
var space = " ";
resultWordArray.push(space);
} else {
var splitWord = word.split("");
var reversedLettersArray = [];
splitWord.forEach(letter => {
reversedLettersArray.unshift(letter);
var reversedWord = reversedLettersArray.join("");
resultWordArray.push(reversedWord);
})
}
})
var finalResult = resultWordArray.join(" ");
console.log(finalResult);
}
reverseWords("Reverse this line");
This code currently outputs:
"R eR veR eveR reveR sreveR esreveR t ht iht siht l il nil enil"
What could be causing the discrepancy here?