Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an array of objects I need to sort on a custom function. Since I want to do this several times on several object attributes, I'd like to pass the key name for the attribute dynamically into the custom sort function:

function compareOnOneFixedKey(a, b) {
    a = parseInt(a.oneFixedKey)
    b = parseInt(b.oneFixedKey)
    if (a < b) return -1
    if (a > b) return 1
        return 0
}
    
arrayOfObjects.sort(compareByThisKey)

This should become something like:

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

Can this be done in a convenient way?

like image 772
paolo.caminiti Avatar asked Jan 24 '13 00:01

paolo.caminiti


People also ask

How do you customize a sort function?

To define custom sort function, you need to compare first value with second value. If first value is greater than the second value, return -1. If first value is less than the second value, return 1 otherwise return 0. The above process will sort the data in descending order.

Does sort JavaScript mutate?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


1 Answers

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"));
like image 166
VisioN Avatar answered Sep 20 '22 16:09

VisioN