Reputation: 127
const data = [
{
Team : "A",
Member : "James",
"Leads" : 305,
closedLeads : 35
},
{
Team : "C",
Member : "Mike",
"Leads" : 305,
closedLeads : 35
}
]
This is my data and I want to sort them based on their team name in descending order of their Leads. First team name and then all the members within team. And members should be in ascending order of their Leads value.
Upvotes: 1
Views: 98
Reputation: 2720
const data = [
{
Team: "A",
Member: "James",
"Leads": 305,
closedLeads: 35
},
{
Team: "C",
Member: "Mike",
"Leads": 305,
closedLeads: 35
},
{
Team: "C",
Member: "Mike",
"Leads": 302,
closedLeads: 35
}
];
data.sort((a, b) => (a.Team < b.Team) ? 1 : (a.Team === b.Team) ? ((a.Leads > b.Leads) ? 1 : -1) : -1 );
console.log(data);
Explanation:
You can use the sort()
method of Array
.
It takes a callback function which also takes 2 objects as parameters contained in the array (which we can call them as a
and b
):
data.sort((a, b) => (a.Team < b.Team) ? 1 : -1);
When it returns 1, the function communicates to sort()
that the object b
takes precedence in sorting over the object a
.
Returning -1 would do the reverse.
The callback function can calculate other properties too. When the Team is the same, you can order by a secondary property(Here Leads
) like this:
data.sort((a, b) => (a.Team < b.Team) ? 1 : (a.Team === b.Team) ? ((a.Leads > b.Leads) ? 1 : -1) : -1 );
Here I have sorted Teams(if they have the same name) in ascending order by comparing their Leads
value. You can check Member
instead of Team
as well.
Upvotes: 2
Reputation: 2753
const data = [
{
Team : "A",
Member : "James",
"Leads" : 305,
closedLeads : 35
},
{
Team : "C",
Member : "Mike",
"Leads" : 305,
closedLeads : 35
}
]
const sorted = data
.sort((a, b) => a.Member.localeCompare(b.Meber))
.sort((a, b) => a.Team.localeCompare(b.Team))
console.log(sorted)
Upvotes: 0