sorting methods for arrays in JavaScript
The most used of course is the encapsulated sort () method.
One: How the Sort () method is used.
The sort method is not as easy to use as we think, not simply Arr.sort (), which requires us to define the callback function inside. Because the sort () method arranges the array items in ascending order by default, the sort () method calls the ToString () transformation method, and then compares the resulting string, even if we compare numbers, and then sort the numbers later.
Take a look at the following example:
var arr1 = [0, 1, 3, ten, 5, 9, 0, 3];
var arr2 = [' Bangbang ', ' father ', ' mother ', ' brother ', ' sister ', true, False, 0, 1, 6,];
Console.log (Arr1.sort ())//Obviously, this is not the result we want [0, 0, 1, 3, 5]
Console.log (Arr2.sort ());//[0,1,13,6, ' bang Bang ', ' brother ', false, ' father ', ' mother ', ' sister ', true]
//After the custom callback function is passed in.
function Ascend (a,b) {return
a-b;
}
Descending order
function descend (a,b) {return
b-a;
}
Console.log (Arr1.sort (Ascend)); [0, 0, 1, ten, 3, 3, 5, 9]
Console.log (Arr1.sort (descend)); [16, 10, 9, 5, 3, 3, 1, 0, 0]
1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15
Two: Sort the two-dimensional array with the sort method.
var arr1 = [[4,5,7],[11,3,6,100,77],[12,9,12,10],[3,1,2,99,22]];
function Ascend (x,y) {return
x[3]-y[3]; In ascending order of the 4th value of the array
}
function descend (x,y) {return
y[0]-x[0]; In ascending order of the 1th value of the array
}
Console.log (Arr1.sort (Ascend));
Console.log (Arr1.sort (descend));
1 2 3 4 5 6 7 8 9
Of course there are other sorting methods, once again I just said encapsulation good, in fact, there are many kinds of sorting, the key to see how you use.
Three: By the way what is the reverse () method. How to use.
The reverse method reverses the order of the array items, looking at the following example:
var arr1 = [0, 1, 3, 10, 16, 5, 9, 0, 3];
var arr2 = [' Bangbang ', ' father ', ' mother ', ' brother ', ' sister ', true, False, 0, 1, 6, 13]; Console.log (Arr1.reverse ());//[3, 0, 9, 5, N, 3, 1, 0] Console.log (arr2.reverse ());//[13,6,1,0,false,true, ' sister ' , ' brother ', ' mother ', ' father ', ' Bangbang ']