Skip to content Skip to sidebar Skip to footer

Variable Function Name Javascript

I'm sorting array: myArray.sort(comparators.some_comparator); and I have several comparator to choose from: comparators = { asc_firstname_comparator : function(o1, o2){ ..

Solution 1:

use the subscript notation for indexing the javascript object (obj.prop is the same as obj["prop"], but the latter way you can create property names dynamically):

functionchooseComparator(field, order){ 

  return comparators[order+"_"+field+"_comparator"]; 

}

and yes, you have to pass a function object to the sort() function, just a name is not enough

Solution 2:

Actually you can create a closure instead of writing dozens of functions. Assuming asc_firstname_comparator means "sort by x.firstname",

functioncompareByProperty(field, order) {
   returnfunction (o1, o2) {
      var retval;
      if (o1[field] > o2[field])
        retval = 1;
      elseif (o1[field] < o2[field])
        retval = -1;
      else
        retval = 0;
      if (order === "desc")
        retval = -retval;
      return retval;
   }
}
...
myArray.sort(compareByProperty("firstname", "asc"));

Solution 3:

I'd do something like this.

var comparators = {
   asc_firstname_comparator : function(o1, o2){ ... }
   desc_firstname_comparator : function(o1, o2){ ... }
};

Array.prototype.customSort(comparatorName) {
    this.sort(comparators[comparatorName]);
}

var myArray = [ ... ]; // define array
myArray.customSort("asc_firstname_comparator");

Post a Comment for "Variable Function Name Javascript"