Today, the sort function of the array can accept the custom comparison function, which is really a wonderful thing. In this way, it is very easy to sort (numbers within the range. VarmyArray [-80,-13.888,-10,-9.6,-9.4,-5.823,-7.999 ,... syntaxHig today finds that the sort function of the array can accept the custom comparison function, which is really a wonderful thing. In this way, it is very easy to sort (numbers within the range. Var myArray = [-80,-13.888,-10,-9.6,-9.4,-5.823,-7.999, 312,]; iJs. put (myArray. sort (function (a, B) {return a-B}); debugging information:-80,-13.888,-10,-9.6,-9.4, 3, 5.823, 7.999, 20, 22, 55,312 If You Want To descending order, change a-B to B-a: var myArray = [-80,-13.888,-10,-9.6, -9.4,-5.823, 7.999, 55,312, 0,]; iJs. put (myArray. sort (function (a, B) {return B-a}); // debug information for B-a: 7.999, 5.823, -1,-9.4,-9.6 ,-10,-13.888,-80 construct the function that returns the comparison function to achieve a more flexible purpose. For this reason, I have written a common sorting function for one-dimensional and two-dimensional arrays as follows (for example, for production, it is best to test it again): // ratio of the same type, the ratio type is different from the type specified by the first parameter of option. The ratio type is specified by the second parameter of option. // if it is an object or an array, specify attributes by name or participate in sorting by elements. // if the results are the same, sort the values according to the rules specified by secondby. var by = function (name, option, secondby) {return function (o, p) {var a, B; var sign = 1; // adjust the order var r; // Save the returned value // if it is an object or an array, if (o & typeof o = 'object') {a = o [name];} else {a = o ;} if (p & typeof p = 'object') {B = p [name];} e Lse {B = p;} if (typeof a = typeof B) {// switch (option [0]) is specified by the first parameter of option. {case "desc": sign = 1; break; case "asc": sign =-1; break; default: sign = 1; // default} else {// type is different than type a = typeof a; B = typeof B; // switch (option [1]) {case "desc": sign = 1; break; case "asc": sign =-1; break; default: sign = 1; // default} if (a = B) {r = typeof secondby = "function "? Secondby (o, p): 0; // recursion supports sorting of multiple parameters} else if (
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.