从具有该对象的数组中计数对象并对该对象进行计数

时间:2018-09-03 05:22:06

标签: javascript reactjs reducers

我有此代码段。并希望将重复的applicationType连同applicationType一起计数,并同时对两者进行计数。

   {
    applicationType:"Supplemental Marketing Application",
    createdBy:"System"
},
{
    applicationType:"Supplemental Marketing Application",
    createdBy:"System"
},
{
    applicationType:"Orphan Application",
    createdBy:"System"
},
{
    applicationType:"Orpahn Application",
    createdBy:"System"
},
{
    applicationType:"IND/BB",
    createdBy:"System"
}

我也想同时计算应用程序类型和应用程序类型名称,并想要这样的结果

{
    applicationType:"Supplemental Marketing Application",
    count:"2"
},
{
    applicationType:"Orphan Application",
    count:"2"
},
{
    applicationType:"IND/BB",
    count:"1"
}

applicationType = [Supplemental Marketing Application,Orphan Application,IND/BB]
count = [2,2,1]

2 个答案:

答案 0 :(得分:1)

您可以使用reduce函数,并检查累加器数组中是否存在与原始数组中的值applicationType相匹配的键 如果findIndex ===-1然后使用原始数组中的这些值创建一个新对象,然后推入累加器,否则,如果它已经存在,则更新count的值

let orgArray = [{
    applicationType: "Supplemental Marketing Application",
    createdBy: "System"
  },
  {
    applicationType: "Supplemental Marketing Application",
    createdBy: "System"
  },
  {
    applicationType: "Orphan Application",
    createdBy: "System"
  },
  {
    applicationType: "Orpahn Application",
    createdBy: "System"
  },
  {
    applicationType: "IND/BB",
    createdBy: "System"
  }
]
let newArray = orgArray.reduce(function(acc, curr) {
  let findIndex = acc.findIndex(function(item) {
    return item.applicationType === curr.applicationType
  });

  if (findIndex === -1) {
    let newObj = {}
    newObj.applicationType = curr.applicationType;
    newObj.count = 1
    acc.push(newObj)
  } else {
    acc[findIndex].count += 1

  }


  return acc;


}, []);

console.log(newArray)

答案 1 :(得分:0)

您可以使用Array.reduce()创建按应用程序类型分组的地图。检查应用程序类型是否存在于地图中,如果已经存在于地图中,则将其计数更新1,否则以默认计数1对其进行映射。Object.values()在地图上将为您提供所需的输出:

let arr = [ { applicationType:"Supplemental Marketing Application", createdBy:"System" }, { applicationType:"Supplemental Marketing Application", createdBy:"System" }, { applicationType:"Orphan Application", createdBy:"System" }, { applicationType:"Orphan Application", createdBy:"System" }, { applicationType:"IND/BB", createdBy:"System" } ];

let result = Object.values(arr.reduce((a, curr)=>{
  a[curr.applicationType] = a[curr.applicationType] || {applicationType : curr.applicationType, count : 0} ;
  a[curr.applicationType].count++;
  return a;
},{}));

console.log(result);