Mutable Methods Sort,Reverse methods using in Javascript
We will use Mutable methods Sort,Reverse in array for changing index position Javascript.
String is sorted directly.Integer doen't directly sorted add compare function.
SORT =
array1.sort(function (x, y)
{
return x - y; // x and y compare first and second return lowest first,highest second place
});
REVERSE = var array2 = [20, 100, 40, 80, 60];
array2.sort(function (x, y) {
return y - x; // y and x compare first and second return Highest first,Lowest second place
});
DEMO
HTML CODING
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sort,Reverse methods using in Javascript (Mutable Methods)</title>
<script type="text/javascript">
function Sort_Reverse()
{
//
String sorted directly
var array = ["Program","Dot","Net"];
array.sort();
alert("Original = Program,Dot,Net " + " Sorted Array = " + array);
//
Integer Numbers Sorted
var array1 = [20, 100, 40, 80, 60];
array1.sort(function (x, y)
{
return x - y; // x and y compare first and second return lowest
first,highest second place
}); // compare 20 - 100 sort = 20,100
alert("Ascending = "+
array1); // compare 100 - 40
sort = 40,100
// compare 100 -80
sort = 80,100
// compare 100 -60 sort = 60,100
// Integer
Number Unsorted
var array2 = [20, 100, 40, 80, 60];
array2.sort(function (x, y) {
return y - x; // y and x compare first and second return Highest
first,Lowest second place
});
alert("Descending = "+array2);
//
Integer Reverse Method
var array3 = [20, 100, 40, 80, 60];
array3.sort(function (x, y) {
return x - y;
}).reverse();
alert("Reverse Method = " + array3);
}
</script>
</head>
<body onload="Sort_Reverse();">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Add new Javascript function for Mutable Methods use sort and Reverse - sort method String directly sorting and Integer only compart two elements[x-y]
Reverse method String directly reversing and Integer only compart two elements[y-x]
0 comments:
Post a Comment