Sort sort method of array Array
- 2021-07-21 07:28:23
- OfStack
The Array object in JavaScript has its own sort method sort (), which sorts the data items in the array, but sometimes the sort results are not satisfactory, such as
var arr = [12, 1, 2, 21, 3];
arr.sort();
alert(arr); The result is 1,12,2,21,3
Why is this? Because the sort in JavaScript defaults to the ascii character code, that is, the numbers are also sorted in their string form.
var strArr = ['a', '2', 'a2', '2a', 'b', '3'];
alert(strArr.sort());
What's the result of this? 2, 2a, 3, a, a2, b
Because the number's ascii code is smaller than the letter's, the number comes first and the letter comes last.
If you want to continue to sort the above array arr by number, what should you do?
JavaScript gives us an entry to pass a parameter, a comparison function, to the sort () method to tell the sorting algorithm whether the value is greater than, less than, or equal to the value.
A comparison function is a function with a specific algorithm.
function compare_fn(value1, value2) {
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
Pass the comparison function compare_fn to sort, sort, and output
arr.sort(compare_fn);
alert(arr); Get 1, 2, 3, 12, 21
The return value of sort method of Array object in JavaScript is defined as
Negative value: If the first parameter passed is smaller than the second parameter
Zero: Two values are equal
Positive value: If the first parameter is larger than the second parameter
The above comparison function can also be abbreviated as
function compare_fn(value1, value2) {
return value1 - value2;
}
This comparison is arranged in ascending order
If you want to arrange in descending order, just change the sign of the return value above, and reverse all returns.
The comparison function for abbreviation is
function compare_fn(value1, value2) {
return -(value1 - value2);
}
I.e.
function compare_fn(value1, value2) {
return value2 - value1;
}
The simple notation is: the order rises; Drop in reverse order.