1) A simple sort: For a general array you can use sort directly, the default is ascending;
var values = [13245];values.sort ();
2) sort itself can accept a parameter, is a reference to a function object, to implement a custom sort;
function Compare (value1, value2) {if(Value1 <value2) { return-1; } if(Value1 >value2) { return 1; } Else { return 0; }}varvalues= [1,3,2,4,5]; Values.sort (compare);
3) In order to specify the sort by object's attributes, we can define a function that takes a property, returns a function, and implements the function as a sort parameter.
function Createcomparisonfunction (PropertyName) {returnfunction (Object1, object2) {varValue1 =Object1[propertyname]; varvalue2 =Object2[propertyname]; if(Value1 <value2) { return-1; } if(Value1 >value2) { return 1; } Else { return 0; } };}vardata = [{name:"Zachary", Age: -}, {name:"Kin", Age: +}];d Ata.sort (createcomparisonfunction (" Age"));
At the same time the above methods can be targeted at our custom objects (classes), as follows:
function Createcomparisonfunction (PropertyName) {returnfunction (Object1, object2) {varValue1 =Object1[propertyname]; varvalue2 =Object2[propertyname]; if(Value1 <value2) { return-1; } if(Value1 >value2) { return 1; } Else { return 0; } };} function person (name, age) { This. Name =name; This. age=Age ; This. Friends = ["Shelby","Court"];}//@overwirte the prototypePerson.prototype ={Constructor:person, sayname:function () {Console.log ( This. Name); }};varPerson1 =NewPerson ("Nicholas", in);varPerson2 =NewPerson ("Kin", +);varPerson3 =NewPerson ("Mike", -);varPersonset =[Person1, Person2, Person3]; Personset.sort (Createcomparisonfunction (" Age"));
JavaScript sorting issues