简体   繁体   中英

how to group by and total sum array of object in javascript?

After I use reduce() to group the objects in an array by month-year:

let groupByMonth;
if (newlistTaskEvaluation) {
    groupDataByMonth = newlistTaskEvaluation.reduce((groups, item) => {
     groups[item.time] = [...groups[item.time] || [], item];
      return groups;
     }, {});
}

I have an array of event objects formatted by group month-year as follows:

groupByMonth = {
    '7-2020': [ //july
        {
            time: "7-2020",
            task: [
                { code: "p1", value: 123 },
                { code: "p2", value: 234 },
            ]
        },
        {
            time: "7-2020",
            task: [
                { code: "p1", value: 345 },
                { code: "p2", value: 456 },
            ]
        },
    ],
    '8-2020': [ //august
        {
            time: "8-2020",
            task: [
                { code: "p1", value: 567 },
                { code: "p2", value: 678 },
            ]
        },
        {
            time: "8-2020",
            task: [
                { code: "p1", value: 789 },
                { code: "p2", value: 999 },
            ]
        },
    ]
}

How to group object of Array by key 'code', time and total sum by value?

Expected result:

output = [
    {
        time: "7-2020", //total month 7-2020
        task: [
            { code: "p1", valueSum: 468 }, // 123 + 345
            { code: "p2", valueSum: 690 }, // 234 +456
        ] 
    },
    {
        time: "8-2020",
        task: [
            { code: "p1", valueSum: 1356 }, // 567 + 789
            { code: "p2", valueSum: 1677 }, // 999 +678
        ]
    }
]

Please help me.

You could try something like this

const output = Object.entries(groupByMonth).map(([time, datapoints]) => {
  const codes = {}
  const allTasks = datapoints.flatMap(point => point.task)
  for (const { code, value } of allTasks) {
    codes[code] = (codes[code] || 0) + value
  }
  return {
    time,
    tasks: Object.entries(codes).map(([code, value]) => ({ code, value }))
  }
}

Though one downside is that the time complexity isn't perfect because of the structure of the data

    const groupByMonth = {
  "7-2020": [
    //july
    {
      time: "7-2020",
      task: [
        { code: "p1", value: 123 },
        { code: "p2", value: 234 },
      ],
    },
    {
      time: "7-2020",
      task: [
        { code: "p1", value: 345 },
        { code: "p2", value: 456 },
      ],
    },
  ],
  "8-2020": [
    //august
    {
      time: "8-2020",
      task: [
        { code: "p1", value: 567 },
        { code: "p2", value: 678 },
      ],
    },
    {
      time: "8-2020",
      task: [
        { code: "p1", value: 789 },
        { code: "p2", value: 999 },
      ],
    },
  ],
};

const result = Object.keys(groupByMonth).reduce((arr, key)=>{
  const task = (groupByMonth[key]).reduce((acc, rec) => {
    return [...acc, rec.task]
  }, [])
    const newObj = {time: key, task}
    return [...arr, newObj]
}, [])

console.log(JSON.stringify(result, 2, 2))

You can get object's keys and when you iterate over them find out inner objects, then, in every object use another oner reduce to get tasks in that data-type what you need. for iterations i suddenly use reduce() method as a swiss-knife to working with arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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