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