3

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?

3
  • This code looks fine..... Commented Feb 13, 2013 at 8:11
  • yes, not working, javascript sort only accepts the function, the attr is undefined Commented Feb 13, 2013 at 8:11
  • Just as an aside 'is this possible' questions generally aren't a useful addition to SO's body of knowledge. Nor are any yes/no questions really. Most of them can even be answered by quickly consulting the relevant documentation (where you can see the correct signature of methods, etc.). Getting help with implementing a feature correctly is an entirely different thing. Commented Feb 13, 2013 at 8:16

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 used keys:

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

2 Comments

The idea, as i noted in my question, was to write one generic function and not a seperate function for each attribute
Ah, right, I see what you mean. And, of course +1 to Blender ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.