Skip to content Skip to sidebar Skip to footer

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: 4

Solution 1:

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

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


array.sort(function(a, b) {
  returncmp(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) || ....
})

Solution 2:

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;
            }
        }
        return0;
    });
    returnthis;
}

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

Solution 3:

obj.sort(function(item1,item2) {
  if ( item1.Name < item2.Name )
    return -1;
  if ( item1.Name > item2.Name )
    return1;
  return item1.Hours - item2.Hours;
});

Solution 4:

You can sort by Name, then sort elements who have the same name by Hours

Example:

vararray = [{"Name":"ANDY", "Hours":40},
             {"Name":"ANDY", "Hours":50},
             {"Name":"GREG", "Hours":40}];


var sortedArray = array.sort(function(a,b) {
            return (a["Name"] > b["Name"]) ? 1 : -1;
    }).sort(function(a,b) {
            if(a["Name"] == b["Name"])
                return (a["Hours"] < b["Hours"]) ? 1 : -1;
            elsereturn0;
    });

Post a Comment for "Grouped Sorting On A Js Array"