Skip to content
Advertisement

Grouping and summing array objects

I’m having a data sample like this

   this.userData = [
      {id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
      {id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
      {id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
    ]

What I want to achieve with this data is to group it and sum it up so it comes out like this

[
{name: Food, total: 100},
{name: Fuel, total: 30}
]

What the current code I have, I do not get the output as I want.

const data = this.userData;
const groups = data.reduce((groups, item) => ({
  ...groups,
  [item.category]: [...(groups[item.category] || []), item]
}), {});
console.log(groups);

Advertisement

Answer

Try this

const userData = [
      {id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
      {id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
      {id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
    ]

const hashMap = {}

for (const { category, amount } of userData) {
  if (hashMap[category]) {
    hashMap[category].total += amount
  } else {
   hashMap[category] = { name: category, total: amount }
  }
}

const output = Object.values(hashMap)
console.log(output)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement