jQuery sort method for javascript string arrays and numeric arrays

JQuery provides us simple sort() method to sort string arrays.

jQuery sort() method will sort the strings based on ASCII values. So, it is better to have all uppercase letters or all lower case letters for strings in arrays.

jQuery sort() method syntax:

                                         arr1.sort() // where arr1 is the name of the array.

 

In the below example I am explaining how to sort strings and numerics using jQuery sort() method.

 

<html>
    <head>
        <title>javascript arrays using jQuery grep() and match() functions</title>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                //sorting array string elements
                var elems = ['Asp.Net', 'Vb.Net', 'C#.Net', 'Asp.Net MVC', 'Sharepoint']
                //before sorting
                $('#sbs').html(elems.join("<br/>"));
                elems = elems.sort();
                //after sorting
                $('#sas').html(elems.join("<br/>"));

                //sorting array numeric elements
                var elemsn = [32, 67, 12, 2];
                //before sorting
                $('#nbs').html(elemsn.join("<br/>"));
                elemsn = elemsn.sort(function(i, j) {
                    return i - j;
                });
                //after sorting
                $('#nas').html(elemsn.join("<br/>"));

            });   
        </script>
    </head>
    <body>
    <p>Strings before sort</p>
      <div id="sbs"></div>
      <p>strings after sort</p>
      <div id="sas"></div>
     
      <br/><br/>
     
      <p>Numeric before sort</p>
      <div id="nbs"></div>
      <p>Numeric after sort</p>
      <div id="nas"></div>
     
    </body>
</html>

 

elems.sort(); will sort the all elements in array elems. Here we assign the array elements to two <div> tags, one is for before sorting and another one is for after sorting.

 

jQuery sort() method sort the array based on ASCII values. So, it is difficult to start numeric values in normal way because it will consider 12 is less than 5(ASCII value of 1 is less than ASCII value of 5).

For that we use comparison function inside the sort method. Sort() method will send the two values to the comparison function at a time. The comparison function will return the result by subtracting both. So the result will be >0,<0 or =0. Sort() method will submit first value to the return array if the result is >0 or =0. It will perform this operation on all pairs in the array.

 $('#nbs').html(elemsn.join("<br/>"));
                elemsn = elemsn.sort(function(i, j) {
                    return i - j;
                });

The above code will return all the array numeric values in sorted format to the array. After that we are assigning the sorted array to the <div> tag.

 

Download source code: jQuery_sort.zip (35.83 kb)