js sort() custom function how can i pass more parameters?

You may add a wrapper:

function compareOnKey(key) {
    return function(a, b) {
        a = parseInt(a[key], 10);
        b = parseInt(b[key], 10);
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };
}

arrayOfObjects.sort(compareOnKey("myKey"));

You would need to partially apply the function, e.g. using bind:

arrayOfObjects.sort(compareOn.bind(null, 'myKey'));

Or you just make compareOn return the actual sort function, parametrized with the arguments of the outer function (as demonstrated by the others).


Yes, have the comparator returned from a generator which takes a param which is the key you want

function compareByProperty(key) {
    return function (a, b) {
        a = parseInt(a[key], 10);
        b = parseInt(b[key], 10);
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    };
}
arrayOfObjects.sort(compareByProperty('myKey'));

compareByProperty('myKey') returns the function to do the comparing, which is then passed into .sort