1024programmer Java javascript array sorting function_javascript skills

javascript array sorting function_javascript skills

arrayobj.sort(sortfunction);
Parameter: 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 the two 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 sorts a multidimensional 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.

The code is as follows:


Characters:
Characters, the items in sortFunction cannot be directly subtracted like numbers. You need to call the
str1.localeCompare(str2) method for comparison to satisfy the return value. The following is the case of sorting columns 1 and 2 of a multidimensional array.

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]))
});
}


So the sorting function of arrayObject.sort( sortFunction ) is still very powerful. Finally, we can achieve the same function as ORDER BY in SQL statements.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/722287

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索