JavaScript : sorting an array ascending or descending order

In this tutorial learn how to sort an Array in ascending or Descending order in JavaScript. By default, the sort() function sorts values as strings.



<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<button onclick="sortASCArray()">Here click to sort an Asceding</button>

<p id="result"></p>

<script>
var fruits = ["Mango", "Pineapple", "Grape", "Watermelon"];

document.getElementById("result").innerHTML = fruits;

function sortASCArray() {
  fruits.sort();        // First sort the elements of fruits 
  //fruits.reverse();     // Then reverse/descending order 
  document.getElementById("result").innerHTML = fruits;
}

</script>
</body>
</html>
Here compare function for numeric value to sort array.


<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<button onclick="sortASCArray()">Here click to sort an Asceding</button>

<button onclick="sortDESCArray()">Here click to sort an Desceding</button>

<p id="result"></p>

<script>
var marks = [20, 110, 1, 15, 35, 7];
document.getElementById("result").innerHTML = marks;

function sortASCArray() {
   marks.sort(function(a, b){return a - b});
   document.getElementById("result").innerHTML = marks;
}

function sortDESCArray() {
   marks.sort(function(a, b){return b - a});
   document.getElementById("result").innerHTML = marks;
}
</script>
</body>
</html>


No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...