Js array sorting-sort () and js array sorting sort
For sorting an array, the default sort () is sorted by character encoding:
VarTestArray = [3,324,534, 665,];
TestArray. sort ();
Alert (testArray );
Output result: 134 3 324 5345 5654 6546 665
Now we want to sort it by numerical value:
VarTestArray = [3,324,534, 665,];
TestArray. sort (Function(A, B ){ReturnA-B ;});
Alert (testArray );
Here, we pass a comparison function to sort. The logic of the comparison function is: if the difference between the two parameters is less than 0, it means that a must appear before B; otherwise, it is behind B. The output result is:
3 134 324 665 5345 5654 6546,
Another example is to find out all the elements in the array containing the letter 'A'. The specific method is as follows:
Var testArray = ['df ', 'rtr', 'wy', 'dafs', 'dfs ',
'Wefa ', 'tyr', 'rty', 'rty', 'ryt ',
'Afds ', 'Wer', 'te'];
TestArray. sort (function (a, B) {return a. indexOf ('A') =-1? 1:-1 ;});
Alert (testArray );
In this way, all the elements in the array containing the letter 'A' are placed in front of the array. After some simple processing, the search results can be output.
If an object array needs to be sorted by a certain attribute in it, it can be like this: for example, each object element in the array arrayObject has a tagName attribute, now you want to sort by the pinyin order of tagName.
ArrayObject. sort (Function(A, B ){ReturnA. tagName <B. tagName? -1:1 ;});
I think it is quite useful.