Home > Net >  how to group and sum data in foreach javascript
how to group and sum data in foreach javascript

Time:03-27

I have a data in the form of an array object. I will group the data and sum the total based on date and code

const data = [
{code: 8, date:"2022-03-24", total:4},
{code: 8, date:"2022-03-24", total:8},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-25", total:1},]

results to be expected

const result = [
{code: 8, date:"2022-03-24", total:12},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:3},]

CodePudding user response:

you can use reduce usually for these grouping problems. I'm taking the combination of code and date to group. something like "8|2022-03-24".

This is how the intermediate object will look like

{
  8|2022-03-24: {
    code: 8,
    date: "2022-03-24",
    total: 12
  },
  8|2022-03-25: {
    code: 8,
    date: "2022-03-25",
    total: 2
  },
  9|2022-03-24: {
    code: 9,
    date: "2022-03-24",
    total: 4
  },
  9|2022-03-25: {
    code: 9,
    date: "2022-03-25",
    total: 3
  }
}

From that object I'm taking the values using Object.values

const data = [
{code: 8, date:"2022-03-24", total:4},
{code: 8, date:"2022-03-24", total:8},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-25", total:1},]

let grouped = Object.values(data.reduce((acc,{code,date,total})=>{
    acc[code '|' date] = acc[code '|' date] || {code,date,total:0}
  acc[code '|' date].total =total
  return acc;
},{}))

console.log(grouped)

  • Related