我想计算时间统计为真的次数,并计算针对唯一 ID 重复的日期数

i want to count number of time stat is true and count number of dates repeated against unique IDs

使用 id 必须为 stat 和 ttrf 创建一个计数器,并创建新数据,其中名称、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}]

欢迎来到 SO!要得到你想要的,你只需要创建一个reduce function。这是一个例子:

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 formatted = data.reduce((acc, item) => {
  if (!acc[item.id]) {
    acc[item.id] = { 
      id: item.id,
      name: item.name,
      team: item.team,
      stat: 0,
      origianlTtrf: item.ttrf,
      ttrf: 1
    };
  }

  if (item.stat) {
    acc[item.id].stat++;
  } 

  if (item.ttrf !== acc[item.id].originalTtrf) {
    acc[item.id].ttrf++;
  }

  return acc;
}, {});

Object.values(formatted); // the data you want in an array

这里我使用了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);