In Javascript, we know that there are two methods for directly sorting Arrays: reverse () and sort (). Reverse () sorts arrays in reverse order, while sort () sorts arrays in forward order. However, we will find the problem in use. The array sorting method here is not sorted by the number size we imagined, but to change the original data according to the string test results. This is not what we want.
So how can we get what we want to sort by the number size in our thinking. We can compile a function for implementation.
The Code is as follows:
Var values = [0, 1, 5, 10, 15];
// Asc ascending function
Function compareAsc (value1, value2 ){
If (value1> value2 ){
Return 1;
} Else if (value1 <value2 ){
Return-1;
} Else {
Return 0;
}
}
// Desc descending Function
Function compareDesc (value1, value2 ){
If (value1> value2 ){
Return-1;
} Else if (value1 <value2 ){
Return 1;
} Else {
Return 0;
}
}
Values. sort (compareAsc );
Console. log (values); // [0, 1, 5, 10, 15]
Values. sort (compareDesc );
Console. log (values); // [15, 10, 5, 1, 0]