I have an array that contains data similar to this:
var committees = [
{
committee: "Apple Com",
userRole: "Member",
membersNum: 11
},
{
committee: "Orange Com",
userRole: "Member",
membersNum: 9
}, {
committee: "Banana Com",
userRole: "",
membersNum: 13
}, {
committee: "Strawberry Com",
userRole: "Vice President",
membersNum: 15
}, {
committee: "Lemon Com",
userRole: "",
membersNum: 13
},
{
committee: "Mango Com",
userRole: "Chair",
membersNum: 11
},
]
I want them sorted first, by the User Role and then by the Committee. The Committee field will always have a value, while the User Role field sometimes will be null.
Currently, what I am doing to achieve this is break the array into two arrays. The first array will return only items which User Role is not null. The second array returns items which User Role is null. Next, I sort each array by Committee ascendingly and then I concatenate them. Thus the logic goes like this:
//get committees user is member of and committees user is not member of
var memberOf = [];
var nonMemberOf = [];
for(var i=0; i<committees.length; i++){
if(committees[i].userRole){
memberOf.push(committees[i]);
} else {
nonMemberOf.push(committees[i]);
}
}
memberOf.sort(function(a,b){return (a.committee > b.committee) ? 1 : -1; });
nonMemberOf.sort(function(a,b){return (a.committee > b.committee) ? 1 : -1; });
var allComs = memberOf.concat(nonMemberOf);
I've spent more than 3 hours reading and trying to implement what I read on some posts here:
- Javascript sort function. Sort by First then by Second
- Sorting an Array of Objects by two Properties
- Javascript - Sort Array of objects by 2 Properties
I believe that there is a better way doing what I'm doing but just can't figure it out. If someone can shed some light here, I will appreciate that very much.
P.S. I'm not asking for someone to do this for me, I want to understand how to do it. For those who can help, thanks in advance!