The sort () method of array in Javascript actually converts the content to be sorted into a string (called toString ()), and then compares it in the first ASCII code of the string, not the number.
Let's see what the official says:
arrayobj.sort(sortfunction)
Parameters
Arrayobj
Required option. Any Array object.
Sortfunction
Options are available. is the name of the function used to determine the order of the elements. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
Description
The sort method sorts the array objects appropriately, and does not create a new array object during execution.
If you provide a function for the sortfunction parameter, the function must return one of the following values:
- A negative value, if the first argument passed is smaller than the second one.
- 0, if two parameters are equal.
- Positive value if the first argument is larger than the second argument.
var arr = [1,3, +]; Arr.sort (); Alert (arr); </script>
Results: 1,25,3
So what do we do? We can write a compare () method
vararr = [1, 3, 25 ]; Arr.sort(compare); //The function name is a reference to the object, so just write the name. alert (arr); functionCompare (NUM1, num2) {varTemp1 =parseint (NUM1); varTemp2 =parseint (num2); if(Temp1 <Temp2) { return-1; } Else if(Temp1 = =Temp2) { return0; } Else { return1; } }</script>Results: 1,3,25
We can rewrite the above code into anonymous classes:
vararr = [1, 3, 25 ]; Arr.sort (function(NUM1, num2) {varTemp1 =parseint (NUM1); varTemp2 =parseint (num2); if(Temp1 <Temp2) { return-1; } Else if(Temp1 = =Temp2) { return0; } Else { return1; }}) alert (arr);</script>As a result: 1, 3, 25
Example: Given a list, the elements are positive integers that require the maximum number of these elements to be returned. For example "5,3,31,2", return 53312
function (i) {return + (I.sort (Compare). Join ('))} function Compare (A, b ) {var as=a+ ', bs=b+ '; return (Bs+as)-(as+BS);}
Reference: http://www.cnblogs.com/backpacker/archive/2012/08/02/2619200.html
The sort () and compare () methods of array in Javascript