Js array sorting-sort () and js array sorting sort

Source: Internet
Author: User

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.


Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.