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, whose return value is as follows: If A is less than B, a should appear before B in the sorted array, then return a less than0the value. If a equals B, it returns0. If a is greater than B, it returns a value greater than0the value. Example 1: We will create an array and sort alphabetically:<script type= "Text/javascript" >vararr =NewArray (6) arr[0] = "George"arr[1] = "John"arr[2] = "Thomas"arr[3] = "James"arr[4] = "Adrew"arr[5] = "Martin"document.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 alphabetically:<script type= "Text/javascript" >vararr =NewArray (6) arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write (arr+ "<br/>") document.write (Arr.sort ())</script>Output:10,5,40,25,1000,11,10,1000,25,40,5Note that the above code does not sort numbers by numeric values, and to do this, you must use a sort function:<script type= "Text/javascript" >functionSortnumber (A, b) {returnAB}vararr =NewArray (6) arr[0] = "10"arr[1] = "5"arr[2] = "40"arr[3] = "25"arr[4] = "1000"arr[5] = "1"document.write (arr+ "<br/>") document.write (Arr.sort (sortnumber) )</script>Output:10,5,40,25,1000,11,5,10,25,40,1000
The sort in JS