Program Code – Sorting Numbers and Strings

Sorting numbers. We use built-in functions of javascript to sort the values ascending in an array.

Here, we create an array called “numbers” with values.

var numbers =["4","7","9","1"];

we use .sort() function to sort it. Before .sort() you should be adding the array variable. In this case,

numbers.sort()

This will sort the items in ascending order. To sort descending,

numbers.sort();
numbers.reverse();
<html>
    <h1 align=" center"> Sorting Numbers and Strings</h1>
    <head>
        <title>Sorting Numbers and Strings</title>
        <script type="text/javascript">
            var fruits =["Banana","Orange","Apple","Mango"];
            var numbers =["4","7","9","1"];

            document.writeln("Sorting fruits:"+fruits.sort() + "<br>");    
/*  This command is sort the fruits name in alaphabetic order */
/* you can use numbers.revese(); function to order the values in descending order */
              
            document.writeln("sorting numbers:"+numbers.sort()); 
 /*  This command is sort the numbers and print into the screen */
              
         </script>
    </head>
    <body>
        <form action=""> </form>
    </body>
</html>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.