Search code examples
javascriptarraysfunctioncounterlistobject

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


using id have to make a counter for stat and ttrf and create new data with name, id, number of stat and number of ttrf repeated against unique 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"}]

Output to be obtained:

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

Solution

  • Here i've used reduce method to solve this issue. You can check this solution.

    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);