Array sorting methods in JavaScript
The most used of course is the packaged sort () method.
One: How does the sort () method work?
The sort method is not as easy to use as we think, it is not simply Arr.sort (), we need to define the callback function inside! Because the sort () method by default arranges array items in ascending order, the sort () method calls the ToString () transformation method and then compares the resulting string, even if we compare numbers, and he also turns the numbers into strings and sorts them later .
Take a look at the following example:
varARR1 = [0,1,3,Ten, -,5,9,0,3];varARR2 = ['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, ten, 3, 3, 5, 9]Console.log (Arr2.sort ());//[0,1,13,6, ' Bangbang ', ' brother ', false, ' father ', ' mother ', ' sister ', true]//after passing in a custom callback functionfunction Ascend (A, b) {returnA-b;}//Descending arrangementfunction Descend (A, b) {returnB-A;} Console.log (Arr1.sort (Ascend)); //[0, 0, 1, ten, 3, 3, 5, 9]Console.log (Arr1.sort (descend));//[9, 5, 3, 3, 1, 0, 0]
Second: Sort the two-dimensional array with the sorting method.
varARR1 = [[4,5,7],[ One,3,6, -, the],[ A,9, A,Ten],[3,1,2, About, A]];function Ascend (x, y) {returnx[3]-y[3];//in ascending order by the 4th value of the array}function descend (x, y) {returny[0]-x[0];//in ascending order by the 1th value of the array}console.log (Arr1.sort (Ascend)); Console.log (Arr1.sort (descend));
Of course there are other sorting methods, once again I only say packaged, 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, see the following example:
varARR1 = [0,1,3,Ten, -,5,9,0,3];varARR2 = ['Bangbang','Father','Mother','Brother','Sister',true,false,0,1,6, -];console.log (Arr1.reverse ());//[3, 0, 9, 5, +, 3, 1, 0]Console.log (Arr2.reverse ());//[13,6,1,0,false,true, ' sister ', ' brother ', ' mother ', ' father ', ' Bangbang '
Reprint: http://blog.csdn.net/flyingpig2016/article/details/52901977
JS One/two-D array sorting