Home >Web Front-end >JS Tutorial >javascript array sorting function_javascript skills

javascript array sorting function_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:48:04849browse

arrayobj.sort(sortfunction);
Parameters: sortFunction
Optional. is the name of the function used to determine the order of elements. If this parameter is omitted, the elements will be sorted in ascending ASCII character order. The
sort method sorts Array objects appropriately; no new Array objects are created during execution.
If a function is provided for the sortfunction argument, the function must return one of the following values:
A negative value if the first argument passed is smaller than the second argument.
Zero if both arguments are equal.
Positive value if the first parameter is larger than the second parameter.
The above method is very convenient for one-dimensional sorting, but how to do multi-key value sorting like ORDER BY in SQL statements?
Multi-key value sorting of multi-dimensional arrays needs to be more complicated, but there is no need to use loops to solve it. The actual solution is the same.
Numbers:
The following example is to sort a multi-dimensional array of numbers in the order of column 5, column 9, and column 3, like ORDER BY col5, col9, col7 in the SQL statement. When it comes to numbers, you can directly subtract the two items and use the result as the return value.

Copy code The code is as follows:



Character: When the character is
, the items in sortFunction cannot be directly subtracted like numbers. You need to call the
str1.localeCompare(str2) method to do so. Compare to satisfy the return value. The following is the case of sorting columns 1 and 2 of a multidimensional array.
Copy code The code is as follows:

function sortFunction(array) ...{
return array.sort( function(x, y) ...{
return (x[0]==y[0])?(x.localeCompare(y)):(x[0].localeCompare(y [0]))
});
}

Therefore, the sorting function of arrayObject.sort( sortFunction ) is still very powerful, and it can finally implement the same ORDER BY in SQL statements function.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn