English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Array object in JavaScript has its own sort() method, which sorts the items in the array, but sometimes the sorting result is 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 that? Because JavaScript's default sorting is based on ASCII character codes, which means numbers are sorted according to their string representation.
var strArr = ['a', '}}2', 'a2', '2a', 'b', '3']; alert(strArr.sort());
What does this result in? 2,2a,3,a,a2,b
Because the ASCII code of numbers is smaller than that of letters, so numbers are in front and letters are at the back.
How to continue to sort the array arr above in numerical order?
JavaScript provides an entry point that allows you to pass a parameter to the sort() method, namely the comparison function, to tell the sorting algorithm the relationship between values and values is greater than, less than, or equal to.
Comparison functions are functions with specific algorithms.
function compare_fn(value1, value2) { < value1 else if (value2) { return -1; }1 > value2) { return 1; } else { return 0; } }
Pass the comparison function compare_fn to sort, then sort, and then output
arr.sort(compare_fn); alert(arr); gets 1, 2, 3, 12, 21
The definition of the return value of the sort method of the JavaScript Array object is
Negative: if the first parameter passed is less than the second parameter
Zero: the two values are equal
Positive: if the first parameter is greater than the second parameter
The comparison function above can also be abbreviated as
function compare_fn(value1, value2) { return value1 - value2; }
This comparison is for ascending order
If you want to sort in descending order, just change the sign of the return value above, and take the inverse of all returns.
The comparison function for the abbreviated form is
function compare_fn(value1, value2) { return -(value1 - value2); }
that is
function compare_fn(value1, value2) { return value2 - value1; }
The simple notation is: ascending in order; descending in reverse.
This article about the sorting method sort of the array Array is all the content that the editor shares with everyone. Hope it can give everyone a reference, and also hope everyone will support and cheer for the tutorial.