首页 > 解决方案 > 我想计算时间统计为真的次数并计算针对唯一 ID 重复的日期数

问题描述

使用 id 必须为 stat 和 ttrf 创建一个计数器,并创建具有 name、id、stat 数和 ttrf 数的新数据,这些数据与唯一 ID 重复

data = [
0: {id: "51a", name: "Henry", team: "SPP", stat: "true", ttrf: "05/08/2020"}
1: {id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020"}
2: {id: "51a", name: "Henry", team: "SPP", stat: "false", ttrf: "05/08/2020"}
3: {id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020"}]

要获得的输出:

data = [
0: {id: "51a", name: "Henry", team: "SPP", stat: 1, ttrf: 2}
1: {id: "5ea", name: "James", team: "BOPS", stat: 2, ttrf: 2}]

标签: javascriptarraysfunctioncounterlistobject

解决方案


在这里,我使用reduce了方法来解决这个问题。您可以检查此解决方案。

const data = [
  { id: "51a", name: "Henry", team: "SPP", stat: "true", ttrf: "05/08/2020" },
  { id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020" },
  { id: "51a", name: "Henry", team: "SPP", stat: "false", ttrf: "05/08/2020" },
  { id: "5ea", name: "James", team: "BOPS", stat: "true", ttrf: "05/08/2020" },
];

const newData = data.reduce((store, obj) => {
  const statVal = obj.stat === "true" ? 1 : 0;
  const ttrfVal = obj.ttrf ? 1 : 0;
  if (!store[obj.id]) {
    store[obj.id] = obj;
    obj.ttrfDates = new Set();
    obj.ttrfDates.add(obj.ttrf);
    store[obj.id].ttrf = ttrfVal;
    store[obj.id].stat = statVal;
  } else {
    if (!(obj.stat === "true" && store[obj.id].ttrfDates.has(obj.ttrf))) {
      store[obj.id].ttrf++;
    }
    store[obj.id].stat += statVal;
  }
  return store;
}, {});

const modifiedData = Object.values(newData).filter(
  (data) => data.ttrfDates && delete data.ttrfDates
);

console.log(modifiedData);


推荐阅读