Thursday, 24 March 2016

Sort,Reverse methods using in Javascript (Mutable Methods)

No comments    
categories: , ,
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 doesn'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>











0 comments:

Post a Comment