Which built-in method reverses the order of the elements of an array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gosai jahnvi
    New Member
    • Apr 2019
    • 22

    Which built-in method reverses the order of the elements of an array?

    Which built-in method reverses the order of the elements of an array?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    there is an Array method called: reverse

    Comment

    • AjayGohil
      New Member
      • Apr 2019
      • 83

      #3
      You can use revese method of javascript

      example : array_name.reve rse();

      you can try below code:

      Code:
      <!DOCTYPE html>
      <html>
      <body>
      
      <h3>Click the button to reverse the order of the elements in the array.</h3>
      
      <button onclick="myFunction()">Try it</button>
      
      <p id="demo"></p>
      <script>
      var cricketers = ["virat", "Rohit", "hardik", "Rahul"];
      document.getElementById("demo").innerHTML = cricketers;
      
      function myFunction() {
          cricketers.reverse();
        document.getElementById("demo").innerHTML = cricketers;
      }
      </script>
      
      </body>
      </html>

      Comment

      • SioSio
        Contributor
        • Dec 2019
        • 272

        #4
        > var a = [1, 2, 3]
        undefined
        > a
        [1, 2, 3]
        > a.reverse();
        [3, 2, 1]
        > a
        [3, 2, 1]
        > a.slice().rever se();
        [1, 2, 3]
        > a
        [3, 2, 1]

        "a.reverse( );" : Replace the array
        "a.slice().reve rse();" : Display only without replace the array

        Comment

        • gits
          Recognized Expert Moderator Expert
          • May 2007
          • 5388

          #5
          "a.reverse( );" : Replace the array
          "a.slice().reve rse();" : Display only without replace the array
          more accurate would be:

          a.reverse(); - mutates the array a
          a.slice().rever se(); - mutates a new array that was returned by the slice method - so the original array a would stay unmodified

          Comment

          Working...