Skip to content Skip to sidebar Skip to footer

Javascript Access Parameter Inside Custom Sort Function

I have a custom sort function defined & call it as below; myArr.sort(this.sortArrayBy, key); sortArrayBy: function(a, b) { let param = this.get('sortKey'); //How do I get

Solution 1:

You could use a closure over the wanted sort key.

myArr.sort(this.sortArrayBy(key));

sortArrayBy: function (param) {
    return function(a, b) {
        if (a[param] < b[param])
            return -1;
        if (a[param] > b[param])
            return 1;
        return 0;
    };
},

Solution 2:

You can't make this .sort() take an extra parameter. A workaround is to create a function which wraps a custom defined sort function which does take the additional parameter.


You can define your own sort function which takes an extra parameter:

sortArrayBy: function(a, b, param) {
    // ... sort logic here ...
    return 0;
}

Then, at the point you call myArr.sort, you can define a wrapper to this function which only takes the expected two parameters:

var self = this;
var sortFunc = function(a, b) {
    return self.sortArrayBy(a, b, self.get('sortKey'));  
};
myArr.sort(sortFunc, key);

Post a Comment for "Javascript Access Parameter Inside Custom Sort Function"