A detailed description of the array Array.Sort () ordering method in JavaScript

Source: Internet
Author: User

The sort () method for arrays in JavaScript is primarily used to sort the elements of an array. Where the sort () method has an optional parameter. however, This parameter must be a Function. When an array calls the sort () method, if there is no arguments in alphabetical order (character encoding order) of the elements in the array, if you want to sort by other criteria, you need to pass a parameter and be a function that compares two values and returns a number that describes the relative order of the two Values.

1, the number of arrays of small to large order to Sort.

Code:

var arr = [22,12,3,43,56,47,4];arr.sort (); console.log (arr); [3, 4, 0, 56]arr.sort (function (m, n) {if (m < N) return-1else if (m > N) return 1else return}); C Onsole.log (arr); [3, 4, 12, 22, 43, 47, 56]

2. Performs a case-insensitive alphabetical order on a string array.

Code:

var arr = [' abc ', ' DEF ', ' BoC ', ' FED ']; Console.log (arr.sort ()); ["BoC", "Def", "FED", "abc"] console.log (arr.sort (function (s, t) {     var a = s.tolowercase ();    var b = t.tolowercase ();    If (a < B) return-1;    If (a > B) return 1;    Return 0; })); ["abc", "BoC", "Def", "FED")

3. Sort the array containing the objects, which is ordered from large to small according to the age of the Object.

Code:

var arr = [{' name ': ' Zhang San ', age:26},{' name ': ' John Doe ', age:12},{' name ': ' Harry ', age:37},{' name ': ' Zhao Liu ', age:4}];var Objectarray Sort = function (keyName) {return function (objectn, Objectm) {var Valuen = Objectn[keyname]var Valuem = objectm[keyname]i F (valuen < Valuem) return 1else if (valuen > Valuem) return-1else return 0}}arr.sort (objectarraysort (' age ')) Consol E.log (arr)//[{' name ': ' Harry ', age:37},{' name ': ' Zhang San ', age:26},{' name ': ' John Doe ', age:12},{' name ': ' Zhao Liu ', age:4}]

 

A detailed description of the array Array.Sort () ordering method in JavaScript

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.