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?

Control Freak
  • 12,573
  • 28
  • 89
  • 143
  • 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,721
  • 5
  • 26
  • 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
  • 55,449
  • 64
  • 175
  • 266
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
  • 204,715
  • 48
  • 286
  • 369
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
  • 13,747
  • 4
  • 54
  • 43