5
var availableTags = [
    {value:"fruit",desc:"fruit",groupId:2,userId:4},
    {value:"aGan",desc:"normal user",groupId:4,userId:5},
    {value:"father's home ",desc:"normal user",groupId:2,userId:4}     

  ].sort(function(a, b) {  return a.groupId > b.groupId; });

This sorts by groupId field, but how do I to sort by groupId and value?

Nerijus G
  • 918
  • 13
  • 28
Control Freak
  • 12,965
  • 30
  • 94
  • 145
  • It might be useful for you to know that `a.groupId > b.groupId` may return incorrect results, depending on your browser. See http://stackoverflow.com/q/9375788/989121 – georg Feb 21 '12 at 10:50

4 Answers4

7

Change the return statement to

return a.groupId > b.groupId || (a.groupId == b.groupId && a.value > b.value);
Philip Sheard
  • 5,789
  • 5
  • 27
  • 42
2

How about

.sort(function (a, b) {
    var firstGroupId = a.groupId;
    var secondGroupId = b.groupId;

    return (firstGroupId === secondGroupId) ? a.value > b.value : firstGroupId > secondGroupId;
});
helpermethod
  • 59,493
  • 71
  • 188
  • 276
1

Copying my recent answer

cmp = function(a, b) {
    if (a > b) return +1;
    if (a < b) return -1;
    return 0;
}

array.sort(function(a, b) { 
    return cmp(a.groupId,b.groupId) || cmp(a.value,b.value)
})
Community
  • 1
  • 1
georg
  • 211,518
  • 52
  • 313
  • 390
0

Javascript Multi-Criteria Sort

If you want to sort by groupId and value, you can use the sort function that I've pasted below (JsFiddle: http://jsfiddle.net/oahxg4u3/6/). This sort function can also be used to sort by n-values, or by a single value.

Define:

function sortByCriteria(data, criteria) {
    return data.sort(function (a, b) {

        var i, iLen, aChain, bChain;

        i = 0;
        iLen = criteria.length;
        for (i; i < iLen; i++) {        
            aChain += a[criteria[i]];
            bChain += b[criteria[i]];
        }

        return aChain.localeCompare(bChain);
    });
}

Invoke:

var data = [
    {value:"fruit", desc:"fruit", groupId:2, userId:4},
    {value:"aGan", desc:"normal user", groupId:4, userId:5},
    {value:"father's home ", desc:"normal user", groupId:2, userId:4}
];
var criteria = ["groupId", "value"];

sortByCriteria(data, criteria);
tim-montague
  • 16,217
  • 5
  • 62
  • 51