Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customizing the sort functionality of JavaScript arrays

I have this very simple sort method:

sortByNumericAttr : function (a, b,attr){            
        a = a[attr];
        b = b[attr];
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}

the idea here is that I have different objects with different attr that needs sorting (id,type etc.), so i thought instead of writing different sort function for each (where all the difference is only the sorted attribute), I'd write a generic method and pass the attribute to it.

So if it is written like this i can call it like:

arr.sort(utils.sortByNumericAttr,'typeId');

How can I achieve this or a similar effect, based on this function?

like image 404
Tomer Avatar asked Jul 18 '26 14:07

Tomer


1 Answers

You can create a function with another function:

function sort_by(attr) {
    return function(o1, o2) {
        var a = o1[attr];
        var b = o2[attr];

        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    };
}

And then call it like .sort(sort_by('id')).

like image 96
Blender Avatar answered Jul 21 '26 03:07

Blender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!