Rune Jeppesen
Rune Jeppesen

Reputation: 1131

javascript sorting jquery

I am doing i a lot of sorting and currently doing it like this:

function sortby(a, b, prop) {
    if (a[prop].toLowerCase() > b[prop].toLowerCase())
        return 1;
    else
        return -1
}

Used like this:

someArray.sort(function (a, b) { return sortby(a, b, 'propertyname') });

But I suspect it is possible to do something more clever with apply or binding, like

someArray.sort(sortby.bind(a,b,'propertyname'))?

Upvotes: 1

Views: 313

Answers (1)

Alexander R
Alexander R

Reputation: 2476

Yes, this is certainly possible. apply returns the result of a function, so it's not applicable here, however, bind fits.

You may wish to read the MDN docs for Bind.

Since bind works in order, if you alter the order of your parameters this is nice and elegant. Let's change the signature of sortby to: function sortby(prop, a, b) {. Now we can easily tell bind to fix the first parameter:

someArray.sort(sortby.bind(undefined, 'propertyname'));

Note the undefined. The first parameter to bind (as per the docs) is a new this reference. Since we don't use it, we'll pass undefined to say that we don't want to change the context. The next parameter tells bind to create a function which passes a value of 'propertyname' as the first argument to sortby. This gives us a partial function application; returning a function which takes two parameters, calling sortby with the first value that we've already given it, then the two parameters. This function is passed to sort, calling it as it needs.

Manually interpreting the call to bind, it gives you something like this:

someArray.sort(function (a, b) {
    sortby.apply(this, 'propertyname', a, b);
});

Upvotes: 1

Related Questions