Reverse multiple words in vanilla javascript

670 views Asked by At

I have the following list and would like to reverse the order of the words not each letter in the word. I currently have this but its reversing each letter and not the order of the words.

JS:

let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"].toString();
myArray.split("").reverse().join('')

Current output:

raC tsaF ,raC yoT ,eerT llaT ,ekiB ettiL

Desired output:

Bike Litte 
Tree Tall 
Car Toy 
Car Fast 
3

There are 3 answers

0
Get Off My Lawn On BEST ANSWER

You want to split by the comma first, then split on each word in the new array of items and reverse those.

You don't want to reverse the whole thing.

let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"].toString();

let result = items.split(',').map(item => item.split(' ').reverse().join(' ').trim());

console.log(result);

0
Abderrahim Soubai-Elidrisi On

Try this

let items = ["Litte Bike, Tall Tree, Toy Car, Fast Car"];


let revItems = items.map(item => item.split(" ").reverse().join(" "));

console.log(revItems.reverse())
0
L0uis On

As others have stated, you have to split up the elements first, then the individual spaces in each element, and print in reverse.

<!DOCTYPE html>

    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
            p {
                margin: 0px !important;
                padding: 0px !important;
                border: 0px !important;
            }
        </style>
        <script type="text/javascript">
            function foo() {
                let items = ["Litte Bike,Tall Tree,Toy Car,Fast Car"].toString().replace(', ',','); //replace the spaces in the string between separations
                var myarray = items.split(','); //separate all the individual items 
                for (var i = 0; i < myarray.length; i++) { //for each item, split on the space in between words
                    var subArray = myarray[i].split(" "); 
                    //i ignore errors
                    console.log(subArray[1] + " " + subArray[0]); //print the order reversed.
                }
            }
        </script>
    </head>
    <body onload="foo();">

    </body>
    </html>