简体   繁体   English

如何在javascript中使用map?

[英]How to use map in javascript?

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.并且成员应该按其 Leads 值的升序排列。

 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 .您可以使用Arraysort()方法。 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 ):它需要一个回调 function ,它也需要 2 个对象作为数组中包含的参数(我们可以将它们称为ab ):

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 .当它返回 1 时,function 通知sort() object b在排序中优先于object a Returning -1 would do the reverse.返回 -1 则相反。

The callback function can calculate other properties too.回调 function 也可以计算其他属性。 When the Team is the same, you can order by a secondary property(Here Leads ) like this:当团队相同时,您可以按这样的次要属性(Here Leads )进行排序:

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.在这里,我通过比较他们的Leads值按升序对团队(如果他们具有相同的名称)进行排序。 You can check Member instead of Team as well.您也可以检查Member而不是Team

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM