When dealing with arrays, we sometimes need to sort the array, there are many ways to sort, but the best and quickest way is to use the sort method for fast sorting.
Let's take a look at an example:
The code is as follows |
Copy Code |
var arr1 = [6, 3, 4, 1, 2, 5, 7, 3, 0, 9, 8, 10];//Here's an array of numbers. Arr1.sort (function (a,b) { return a-b; }); This method is ascending to the platoon, whereas, Arr1.sort (function (a,b) { return b-a; }); |
This is the descending method of defecation.
Sort by alphabetical
The code is as follows |
Copy Code |
var arr = [' B ', ' CC ', ' abc ', ' Fzj ', ' xij ', ' ACD ', ' Yab ']; Arr.sort (); for (var i = 0; i < arr.length; i++) { Document.writeln (Namearr[i]); } Results: ABC ACD b cc Fzj Xij Yab |
Demo2 numeric sort, sort (Prama) method with parameters
The code is as follows |
Copy Code |
Descending function var desc = function (x,y) { if (x > Y) return-1; Returns a number less than 0. Else return 1; Returns a number greater than 0. } Ascending function var asc = function (x,y) { if (x > Y) return 1; Returns a number greater than 0. Else return-1; Returns a number less than 0. }
var arr2 = [4,6,4,2,7,9,0,1]; Arr2.sort (DESC); Descending sort Document.writeln (ARR2); Document.writeln ("<br>"); Arr2.sort (ASC); Ascending sort Document.writeln (ARR2);
Results: 9,7,6,4,4,2,1,0 0,1,2,4,4,6,7,9 |
A simple algorithm for Demo2
code is as follows |
copy code |
var arr2 = [ 4,6,4,2,7,9,0,1]; Arr2.sort (function (a,b) {return a-b}); Document.writeln (ARR2); Document.writeln ("<br>"); Arr2.sort (function (a,b) {return b-a}) ; Document.writeln (arr2); Result: 0,1,2,4,4,6,7,9 9,7,6,4,4,2,1,0 |