How to Sort and Reverse an Array in JavaScript

Introduction

 
In this blog, we will learn how to sort an array in ascending and descending order. Also, we will learn how to reverse an array string.
 

Sort()

 
The sort() method sorts the elements of an array.
 
The sort order can be either alphabetic or numeric, and either ascending or descending.
 
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
 

Reverse()

 
The reverse() method reverses the elements in an array.
 
Example of sort() and reverse() 
 
Copy the HTML code and paste it to your file. The name extension must be .html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Reverse an Array in Javascript</title>    
  6.     
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9. </head>    
  10. <body>    
  11.     <div>    
  12.         <p>Actual Array :<span id="actual"></span></p>    
  13.         <p>Reversed Array :<span id="reverse"></span></p>    
  14.         <p>Ascending order Sort Array :<span id="asc"></span></p>    
  15.         <p>Descending order Sort Array :<span id="desc"></span></p>    
  16.     </div>    
  17.   <button onclick="sort()">Sort</button>    
  18.   <button onclick="rev()">Reverse</button>    
  19.   <button onclick="desc()">Descending Order</button>    
  20.   <script type="text/javascript">    
  21.     var names=["Jack","Kim","Joe","Suzie","Alex"];    
  22.     document.getElementById("actual").innerHTML =names;    
  23.         
  24.     function rev(){    
  25.         document.getElementById("reverse").innerHTML =names.reverse();    
  26.     }    
  27.     function sort(){    
  28.         names.sort();    
  29.         document.getElementById("asc").innerHTML =names;    
  30.     }    
  31.     function desc(){    
  32.         names.reverse();    
  33.         document.getElementById("desc").innerHTML =names;    
  34.     }    
  35.   </script>    
  36. </body>    
  37. </html>     
Output
 
 
 
Reverse in Descending Order
 

Summary

 
In this blog, I explained Javascript array methods. For any questions, please leave a comment