Reputation: 13233
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
?
Upvotes: 5
Views: 3058
Reputation: 17372
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);
Upvotes: 0
Reputation: 214959
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)
})
Upvotes: 1
Reputation: 62165
How about
.sort(function (a, b) {
var firstGroupId = a.groupId;
var secondGroupId = b.groupId;
return (firstGroupId === secondGroupId) ? a.value > b.value : firstGroupId > secondGroupId;
});
Upvotes: 2
Reputation: 5825
Change the return statement to
return a.groupId > b.groupId || (a.groupId == b.groupId && a.value > b.value);
Upvotes: 7