1
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.

1
  • 4
    you'll want to use sort, not map, to sort Commented Nov 11, 2020 at 5:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the more efficient solution I think
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.