JQuery passes an extra variable to sort the function

I need to write a generic sort function. I use jQuery to sort. The jQuery sorting function accepts only two parameters. But I want to pass another parameter to this function. How can i do this?

Something like that:

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; } 
+4
source share
3 answers

You can create a function that returns a function. The external function takes an additional argument, and you use the returned function as a sort callback method:

 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)); 

An internal function has access to all parameters of an external function, since it is a closure [MDN] .

+11
source

I do not believe jQuery has a sort function at all. JavaScript does, on arrays . jQuery and JavaScript are two different things (one is a library, the other is a language). Update : Ah, jQuery has an undocumented sort (one of several functions that it takes from Array.prototype ), but this fact is not documented and therefore can change from point to point release. Thanks, Felix .

You cannot pass the third argument to a function directly. You can pass the function you pass to sort to call another function:

 // ...assuming `desc` is in scope here here... obj.sort(function(a, b) { return StringSort(a, b, desc); }); 

The same desc will be passed to StringSort for each pair of compared records. a and b , of course, will be different for every call.

This works because the function we pass to sort is a closure in the context in which desc defined. This means that a function can access desc (just as functions can access global variables for the same reason).

More on closing:

+4
source

Try the following:

 function sortBy(field){ return function(a, b){ if (a.field > b.field) return -1; if (a.field < b.field) return 1; return 0; }; } 
0
source

Source: https://habr.com/ru/post/1441258/


All Articles