1

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'))?
2
  • this may help you stackoverflow.com/a/1134983/1075211 Commented Jun 13, 2013 at 10:07
  • 1
    Rather than the > comparison you're doing, you might as well use the built in localecompare and do return a[prop].toLowerCase().localeCompare(b[prop].toLowerCase()); Commented Jun 13, 2013 at 10:52

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent - both solution and explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.