This example describes the JavaScript custom array sorting method. Share to everyone for your reference. The specific analysis is as follows:
Array has its own sorting function, which is convenient to use, we have a point must be clear, is the basis for sorting, if the sort does not pass in the parameters, it is in the order of character encoding (Unicode encoding) sequence.
var a=["3", "2", "1"];
Console.log (a[0].charcodeat (0)); Wuyi
Console.log (a[1].charcodeat (0));//
Console.log (a[2].charcodeat (0));//
Console.log (A.sort ( )); ["1", "2", "3"]
var a=["3", "You", "he"];
Console.log (a[0].charcodeat (0)); Wuyi
Console.log (a[1].charcodeat (0));//20320
Console.log (a[2].charcodeat (0));//20182
Console.log ( A.sort ()); ["3", "he", "you"]
var a=["3", "One", "222"];
Console.log (A.sort ())//["One", "222", "3"]
//Multiple characters are encoded according to the first character
But I think the best thing about sort is that you can customize the sort, which is also more common in practice, such as ordering an array of objects. For example, a line of an object array, based on one of the fields sorted, of course, you can also write a function to complete, but I do not think that the sort came convenient.
var list = [
{
max:3,
avg:2,
min:1
},
{
max:10,
avg:15,
min:20
},
{
Max:8,
avg:5,
min:2
}
];
To sort the list objects by the Max field, the small to large order
//X,y is the single element of the array to compare, here is an element
//Sort method in the list is to provide a comparison of the size of the rules, in other words, is to show who the big and small
//Return value is true or false
function Sortbyfield (x, y) {returns
X.max-y.max;
}
Console.log (List.sort (Sortbyfield));
The effect is as shown in the following illustration:
I hope this article will help you with your JavaScript programming.