2

How can I pass an argument to callback method while calling it from arrayobj.sort(sortFunction) method.I want to pass "sortOrder" to "Compare" as well to sort it accending or desecding.

var sortOrder = "asc";
var a = new Array(4, 11, 2, 10, 3, 1);
b = a.sort(Compare);   // how to pass "sortOrder" here

// Sorts array elements in ascending order numerically.
function Compare(first, second, sortOrder) // here sortOrder require 
{
    if(sortOrder == "asc"){
        if (first == second)
            return 0;
        if (first < second)
            return -1;
        else
            return 1; 
        }
    else{
        if (first == second)
            return 0;
        if (first < second)
            return 1;
        else
            return -1; 
        }


    }
}
1
  • For inline anonymous functions always prefer arrows a.sort((p,c) => compare(p,c)) Commented Apr 14, 2016 at 12:09

3 Answers 3

1

This solution returns a function for the selected sort order. If no order is specified, then the function for asc is used.

function getComparer(sortOrder) {
    return sortOrder === 'desc' ?
        function (a, b) { return b - a; } :
        function (a, b) { return a - b; };
}

var a = new Array(4, 11, 2, 10, 3, 1);

a.sort(getComparer());
document.write('<pre> ' + JSON.stringify(a, 0, 4) + '</pre>');
a.sort(getComparer('desc'));
document.write('<pre> ' + JSON.stringify(a, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

2 Comments

Nice. But I'd suggest changing the name of your "compare" function to something like "generateCompare" or something like that :) , it confused me for a second.
@RubenSerrate, better now?
1

Try this way

Replace

b = a.sort(Compare);

with

b = a.sort(function(a,b){
  return Compare(a, b, sortOrder);
});

DEMO

var sortOrder = "asc";
var a = new Array(4, 11, 2, 10, 3, 1);
b = a.sort(function(a,b){
  return Compare(a, b, sortOrder);
});

document.body.innerHTML += JSON.stringify(b,0,4);

function Compare(first, second, sortOrder) // here sortOrder require
{
    if(sortOrder == "asc"){
        if (first == second)
            return 0;
        if (first < second)
            return -1;
        else
            return 1; 
        }
    else{
        if (first == second)
            return 0;
        if (first < second)
            return 1;
        else
            return -1; 
        }


    }

Comments

0

If the only use for your code is the one you've posted here, you can just remove sortOrder from the list of parameters, so that the variable you define at the top is still visible inside the function.

If not, either of the two previous answers are the way to go.

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.