The sort () method is used to sort elements of an array.
Syntax: Arrayobject.sort (sortby), parameter SortBy Optional. Specifies the sort order. Must be a function.
Note: If the method is called without parameters , the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded . To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B with the following return values:
If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
If a equals B, 0 is returned.
If a is greater than B, a value greater than 0 is returned.
Example 1: We will create an array and sort alphabetically:
<script type= "Text/javascript" >var arr = ["George", "John", "Thomas", "James", "Adrew", "Martin"];d ocument.write ( arr + "<br/>") document.write (Arr.sort ()) </script>
Output:
George,john,thomas,james,adrew,martinadrew,george,james,john,martin,thomas
Example 2: We will create an array and sort from small to large order:
<script type= "Text/javascript" >function Sortnumber (A, b) { return A-b}var arr = [5, 1];d OC Ument.write (arr + "<br/>") document.write (Arr.sort (sortnumber)) </script>
Output:
10,5,40,25,1000,11,5,10,25,40,1000
The use, parameters, and sorting principles of the sort () method in JS