JS comes with the sort () method

Source: Internet
Author: User

1. Overview of methods

Array sort() method defaults to converting all elements to string and then sorting by Unicode.

Sort () changes the original array and returns the array after the change (sort).

2. Example

2.1 If no custom method is provided, the array element is converted to a string and returns the result of the order of the string under Unicode encoding

varFruit = [' cherries ', ' apples ', ' bananas '];fruit.sort (); //[' apples ', ' bananas ', ' cherries ']varscores = [1, 10, 2, 21]; Scores.sort (); //[1, 2, ten]//Watch out of that Ten comes before 2,//because ' comes before ' 2 ' in Unicode code point order.varthings = [' word ', ' word ', ' 1 word ', ' 2 Words '];things.sort (); //[' 1 word ', ' 2 Words ', ' word ', ' word ']//in Unicode, numbers come before upper case letters,//which come before lower case letters.

2.2 Using Map to sort

//The array to be sortedvarlist = [' Delta ', ' alpha ', ' CHARLIE ', ' Bravo '];//temporary array holds objects with position and Sort-valuevarMapped = List.map (function(el, i) {return{index:i, value:el.toLowerCase ()};})//sorting the mapped array containing the reduced valuesMapped.sort (function(A, b) {return+ (A.value > B.value) | | + (A.value = = = B.value)-1;});//container for the resulting ordervarresult = Mapped.map (function(EL) {returnList[el.index];}); alert (result);

Reference Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

   

JS comes with the sort () method

Related Article

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.