We want to sort the array based on an object property. The comparison function passed to the array sort () method is to receive
Two parameters, which is the value to compare. However, we need a way to indicate which property to sort by. To solve this problem,
You can define a function that receives a property name and then creates a comparison function based on the name of the property, and here is the letter
The definition of a number.
1 function Createcomparisonfunction (PropertyName) {2 returnfunction (Object1, object2) {3 varValue1 =Object1[propertyname];4 varvalue2 =Object2[propertyname];5 if(Value1 <value2) {6 return-1;7}Else if(Value1 >value2) {8 return 1;9}Else {Ten return 0; One } A }; -}
1 vardata = [{name:"Zachary", Age: -}, {name:"Nicholas", Age: in}];2Data.sort (Createcomparisonfunction ("name"));3Alert (data[0].name);//Nicholas4Data.sort (Createcomparisonfunction (" Age"));5Alert (data[0].name);//Zachary