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.
<script>
function Numascsort (A, B)
{
return a-B;
}
function Numdescsort (A, B)
{
return b-a;
}
var arr = new Array (3600, 5010, 10100, 801);
Arr.sort (Numdescsort);
Alert (arr); //10100,5010,3600,801
Arr.sort (Numascsort);
Alert (arr); //801,3600,5010,10100
</script>
<script>
var myarray=["Apple", "Orange", "Banana"]
Myarray.sort ()
alert (myarray); //apple, Banana,orange
For object array ordering, we first write a function that constructs a comparison function:
<title>Untitled Document</title><Script>/*var by = function (name) {return function (O, p) {var A, B; if (typeof o = = = "Object" && typeof p = = = = "Object" && o && p) {a = O[name]; b = P[name]; if (a = = b) {return 0; } if (typeof a = = typeof b) {return a < b? -1:1; } return typeof a < typeof B? -1:1; } else {throw ("error"); } }}*/var by= function(Name,minor) {return function(o,p) {varb; if(o&&P&& typeofo=== 'Object' && typeofP==='Object') {a=O[name]; b=P[name]; if(A===b) { return typeofMinor=== 'function' ?minor (o,p):0; } if(typeofa=== typeofb) { returna<b? -1:1; } return typeofa< typeofb? -1 : 1; }Else{thro ("Error"); } }}varEmployees=[]employees[0]={name:"George", Age: +, Retiredate:"March,"}employees[1]={name:"Edward", Age: -, Retiredate:"June 2, 2023"}employees[2]={name:"Christine", Age: -, Retiredate:"December, 2036"}employees[3]={name:"Sarah", Age: +, Retiredate:"April, 2020"}//Employees.sort (by ("Age"));Employees.sort (by (' Age', by ('name')));</Script></Head><Body></Body>
Js-sort sort