The below is the code:
function createComparisonFunction(propertyName){
return function(object1, object2){
var value1 = object1[propertyName];
var value2 = object2[propertyName];
if(value1 < value2){
return -1;
}else if(value1 > value2){
return 1;
}else{
return 0;
}
};
}
var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
data.sort(createComparisonFunction("name"));
alert(data[0].name);
data.sort(createComparisonFunction("age"));
alert(data[0].name);
As you can see the createCompatisonFunction is filled in with value called name and as you can see inside this function, there’s object1 and object2. Can I ask what does these arguments pass in with? Do you catch me?
when sorting elements in
datathe sorting algorithm will have to perform elementary comparison between two elements to determine which one is greater than the other. Thesortmethod of array objects, supplies the comparison function the two objects that it wants to compare. Basically you are defining a < operator of sorts for your object.