-1

please help me with below code.I did not understand the functioning of return function(object1,object2).How does the return function in create comparison function() get its parameters.?

var data = [{ name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];

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; 
     } 
   }; 
}
data.sort( createComparisonFunction(" name")); 
alert( data[ 0]. name); // Nicholas 
data.sort( createComparisonFunction(" age"));
alert( data[ 0]. name); // Zachary
Johnny Bones
  • 8,786
  • 7
  • 52
  • 117

2 Answers2

0

You can assume that sort function is similar to the below code.

function sort( comparefunction )
{
  ...
  if ( comparefunction(obj1, obj2 ){
    // do stuff
  }
}

Now because comaprefunction itself is something like createComparisonFunction("name") you will have something like this in the end: createComparisonFunction("name")(obj1, obj2) which name is the input for createComparisonFunction and obj1, obj2 are the inputs for the nameless function.

Saeid
  • 4,147
  • 7
  • 27
  • 43
0

When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.