Q:

Grouped sorting on a JS array

I have an array of objects with two properties: Name and Hours.
For example:
array = [
    {name: "ANDY", hours: 40 }, 
    {name: "ANDY", hours: 50 }, 
    {name: "GREG", hours: 40 },
]

For example in my array I would like the result of the sorting to have the Andy with the most hours first, then Andy with slightly less hours, and then Greg because his name comes later alphabetically and so on and so on.
Since the array.sort() function passes two elements of the array to compare i realise this is not the way to go for me but fail to come up with an elegant solution. Please help me out.

A:

array = [
    {name: "ANDY", hours: 40 }, 
    {name: "GREG", hours: 40 },
    {name: "ANDY", hours: 50 }, 
]

function cmp(x, y) {
  return x > y ? 1 : (x < y ? -1 : 0);
}


array.sort(function(a, b) {
  return cmp(a.name, b.name) || cmp(b.hours, a.hours)
})

console.log(array)

If javascript had a spaceship operator that would be even more elegant. Note that this code is easy to extend to use more properties:
ary.sort(function(a, b) {
    return cmp(a.name, b.name) || cmp(a.age, b.age) || cmp(b.hours, a.hours) || ....
})

A:

var arr = [{
    name: "GREG",
    hours: "40"
}, {
    name: "ANDY",
    hours: "50"
}, {
    name: "ANDY",
    hours: "40"
}];

Array.prototype.sortOn = function(conds){
    this.sort(function(a, b){
        for(var i=0; i < conds.length; i++){
            var c = conds[i].split(" ");
            if(a[c[0]] < b[c[0]]){
                return c[1] == "asc" ? -1:1;
            }
            if(a[c[0]] > b[c[0]]){
                return c[1] == "asc" ? 1:-1;
            }
        }
        return 0;
    });
    return this;
}

arr.sortOn(["name asc", "hours dsc"]);

