We use the sort() method to sort data from an array.
Sorting in ascending order
<html>
<body>
<script>
var x=["Pineapple","Melon","Orange","Banana","Mango"];
x.sort();
window.alert(x);
</script>
</body>
</html>
Sorting in descending order
Use reverse() method with sort() method
<html>
<body>
<script>
var x=["apple","banana","orange"];
x.sort().reverse();
window.alert(x);
</script>
</body>
</html>
Sorting of numbers in ascending order
<html>
<body>
<script>
var x=[4,1,3,5,2];
x.sort(function(x,y){return x-y});
window.alert(x);
</script>
</body>
</html>
Sorting of numbers in descending order
<html>
<body>
<script>
var x=[4,1,3,5,2];
x.sort(function(x,y){return x-y}).reverse();
window.alert(x);
</script>
</body>
</html>
Other Helpful Posts
Publish A Comment