JavaScript Array Sort Reverse

      No Comments on JavaScript Array Sort Reverse




sort() method in javascript on array is used for sorting.
reverse() method is used to reverse an array in javascript.

Combining both methods sort() and reverse(), an array can sorted in descending manner. First use sort() method to sort an array in ascending order and then use reverse() method to reverse the sorted array.

<!DOCTYPE html>
<html>
<body>

<button onclick="sortCities()">Click Here to Sort </button>
<div id="javascriptSortDemo"></div>

<script>
var cities = ["Patna", "Bangalore", "Mumbai", "Delhi","Agra"];
document.getElementById("javascriptSortDemo").innerHTML = cities;
function sortCities() {
   cities.sort();
   cities.reverse();
   document.getElementById("javascriptSortDemo").innerHTML = cities;
}
</script>

</body>
</html>