ozil
ozil

Reputation: 7117

How can I pass an argument to callback while calling it from sort method

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


    }
}

Upvotes: 2

Views: 49

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386726

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

Upvotes: 1

Ruben Serrate
Ruben Serrate

Reputation: 2783

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.

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

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


    }

Upvotes: 1

Related Questions