The Array.sort() method in javascript is used to sort array items. By default, it is arranged in ascending order. The example code is as follows:
var arrA = [6,2,4,3,5,1];
arrA.sort();
document.writeln (arrA);
//The result is: 1,2,3,4,5,6
The sort() method can accept a method as a parameter. This method has two parameters. Represents the two array items in each sorting comparison.
When sort() sorts, this parameter will be executed every time two array items are compared, and the two compared array items will be passed to this function as parameters. When the function returns a value of 1, the order of the two array items is swapped, otherwise it is not swapped.
The example is as follows:
var arrA = [6, 2,4,3,5,1];
/**//*arrA.sort();
document.writeln(arrA);
*/
function desc(x,y)
...{
if (x > y)
return -1;
if (x < y)
return 1;
}
function asc(x,y)
...{
if (x > ; y)
return 1;
if (x < y)
return -1;
}
arrA.sort(desc); // sort by desc
document. writeln(arrA);
document.writeln("
");
arrA.sort(asc); //sort by asc
document.writeln(arrA);
// Output result:
6,5,4,3,2,1
1,2,3,4,5,6
In addition, you can put an unnamed function directly to the call to the sort() method. The following example is to arrange odd numbers in the front and even numbers in the back. The example is as follows:
var arrA = [6,2,4,3,5,1];
arrA.sort( function(x, y) ...{
if (x % 2 == 0)
return 11;
if (x % 2 !=0)
return -1;
}
);
document.writeln(arrA);
/ /Output: 1,5,3,4,6,2