Javascript| Array
The Array.Sort () method in JavaScript is used to sort the array items by default in ascending order, with the instance code as follows:
var arra = [6,2,4,3,5,1];
Arra.sort ();
Document.writeln (ARRA);
The result: 1,2,3,4,5,6
The sort () method can accept a method as a parameter, and this method has two parameters. Represents each of the two array entries for each sort comparison. Sort () performs this argument each time the comparison of two array entries is performed and passes the two comparison array items as arguments to the function. The order of two array items is exchanged when the function returns a value of 1, otherwise it is not exchanged.
Examples are 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 ("<br>");
Arra.sort (ASC); Sort by ASC
Document.writeln (ARRA);
Output results:
6,5,4,3,2,1
1,2,3,4,5,6
Alternatively, a nameless function can be directly placed in a call to the sort () method. The example below is an odd number in front and an even number in the following example:
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