I need to write a common sort function. I am using jQuery for sorting. jQuery sort function only accepts two parameters as input. But I want to pass another parameter to that function. How can I do that?
Something like this:
obj.sort(StringSort);
obj2.sort(StringSort);
function StringSort(a, b, desc)
{
var aText = $(a).attr(desc).toLowerCase();
var bText = $(b).attr(desc).toLowerCase();
if(aText == bText)
return 0;
return aText > bText ? 1 : -1;
}
You can create a function that returns a function. The outer function accepts the additional argument and you use the returned function as sorting callback:
function getStringSort(desc) {
return function(a, b) {
// this is a closure, you can access desc here
// this function should contain your comparison logic or you just
// call StringSort here passing a, b and desc.
}
}
obj.sort(getStringSort(someValue));
The inner function has access to all parameters of the outer function since it is a closure [MDN].
I don't believe jQuery has a sort
function at all. JavaScript does, on arrays. jQuery and JavaScript are different things (one is a library, the other is a language). Update: Ah, jQuery has an undocumented sort
(one of several functions it borrows from Array.prototype
), but that fact is not documented and so could change from dot release to dot release. Thanks, Felix.
You can't pass a third argument into the function directly. You can have the function you pass into sort
call another function:
// ...assuming `desc` is in scope here here...
obj.sort(function(a, b) {
return StringSort(a, b, desc);
});
The same desc
will get passed to StringSort
for each pair of entries being compared. a
and b
, of course, will be different on each call.
This works because the function we're passing into sort
is a closure over the context in which desc
is defined. That means the function can access desc
(just as functions can access global variables, and for the same reason).
More on closures:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With