0

I have a number of pages with sortable columns, the code is like

            var invert = $('...').val();
            var column = $('...').val();
            $list.children().detach().sort(function (a,b) { 
                var aa = $(a).find('.'+column).html().trim();
                var bb = $(b).find('.'+column).html().trim();
                // conversions cut off
                return invert ? aa-bb : bb-aa;
            }).appendTo($list);

where column is a class of the column to sort. I'd like to make it one callback function instead of repeating the code

function column_sorter(a, b) {
    var aa = $(a).find('.'+column).html().trim();
    // ....
}

$list.children().detach().sort(column_sorter).appendTo($list);

but column is inaccessible here (and invert probably - too). Is there any possibility to utilize the function here?

1
  • Can you add a full reproducible snippet of the code you desire to write and fails? I would be happy to fix it, but as it stands, I doubt that function-scoped variables are not seen by functions of their scope. This very much seems that you have separate functions and one function tries to access a function-scoped variable that is inside another function. Commented Oct 29, 2021 at 9:19

2 Answers 2

4

Is there any possibility to utilize the function here?

You'll have to pass that contextual information to the function. Often the way to do that is to have a function that returns another function, and have sort call the returned function:

function column_sorter(column/*, ...anything else it needs...*/) {
    return function(a, b) {
        var aa = $(a).find('.'+column).html().trim();
        // ....
    };
}

$list.children().detach().sort(column_sorter(column/*, ...*/)).appendTo($list);

Side note: If the function need this to be controlled by sort (usually it doesn't), I'd probably make it an arrow function:

function column_sorter(column/*, ...anything else it needs...*/) {
    return (a, b) => {
        var aa = $(a).find('.'+column).html().trim();
        // ....
    };
}

$list.children().detach().sort(column_sorter(column/*, ...*/)).appendTo($list);
Sign up to request clarification or add additional context in comments.

Comments

0

Its as simple as this

function sort_function(a, b, c) {
  console.log(c);
  return a - b;
}
const arr = [4, 1, 5, 3, 2];
c = "test";
arr.sort((a, b) => sort_function(a, b, c));
console.log(arr);

So you could use it as

function column_sorter(a, b, c) {
    var aa = $(a).find('.'+column).html().trim();
    // ....
}

$list.children().detach().sort((a, b) => column_sorter(a, b, c)).appendTo($list);

Comments

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.