Setting up JavaScript array sorting functions

I have this very simple sorting 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 require sorting (id, type, etc.), so I thought instead of writing different sorting functions for each (where all the difference is just the sorted attribute ), I'd write a generic method and pass an attribute to it.

So if it's written like this, I can call it like this:

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

      

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

+3


source to share


2 answers


You can create a function with a different 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'))

.

+8


source


If you have a list like this:

var list = [
    {id:5, color:"Green", name:"Audi"},
    {id:1, color:"Red", name:"Ferrari"},
    {id:3, color:"Silver", name:"Mercedes"}
];

      



You can create sort functions to sort this list for each of the keys used:

function sortById(a,b) { return (a.id-b.id); }
list.sort(sortById);

function sortByName(a,b) { return (a.name.localeCompare(b.name)); }
list.sort(sortByName);

function sortByColor(a,b) { return (a.color.localeCompare(b.color)); }
list.sort(sortByColor);

      

0


source







All Articles