JavaScript one line solution


  • 1
    E
    var reverseWords = function(str) {
        return str.split(" ").reverse().filter(function(v){return v}).join(" ");
    };
    

  • 0
    T

    @elvisnoopy said in JavaScript one line solution:

    .filter(function(v){return v})

    Nice one! You might simplify the filter to .filter(Boolean).


  • 0
    S

    *** UPDATE: I see now that filter function is just removing falsy values. Really great job @thistlethursday !

    Could you explain what the .filter( ) function is doing here ? I wrote very similar code but love how simple yours is due to the filter function. Very great solution!


  • 0
    F

    @spark4 The string is split into chunks by the space character. "A B".plit(" ") (3 spaces) will result in the array ["A", "", "", "B"]. Filtering on non-empty items will reduce that array to ["A", "B"] (ie only the actual words). Joining the array by spaces will reconstruct correct words.

    (Note that this can go slightly faster by trimming the string first)


  • 0
    S

    My version:

    var reverseWords = function(str) {
            return str.trim().split(/ +/).reverse().join(' ');
    };
    

    Runs 105 ms.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.