Recently I took on the challenge of solving the Reverse words Codewars exercise, and after some trial and error, I finally managed to get it right. However, I ran into a problem with a solution that seemed correct but wasn't working as expected. Even though I couldn't figure out why at first glance (I'm sure the answer is right in front of me). The code below returns the string as normal, without reversing it:
function reverseWords(str) {
let wordsArr = str.split(" ");
wordsArr.map(e => e.split("").reverse().join(""));
return wordsArr.join(" ");
}
However, by chaining all the methods instead of using map directly on wordsArr, the solution works fine:
function reverseWords(str) {
let wordsArr = str.split(" ").map(e => e.split("").reverse().join(""));
return wordsArr.join(" ");
}
I am curious as to why this approach worked when the previous one didn't. Any insights would be appreciated. Thank you!