I’m having a data sample like this
JavaScript
x
6
1
this.userData = [
2
{id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
3
{id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
4
{id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
5
]
6
What I want to achieve with this data is to group it and sum it up so it comes out like this
JavaScript
1
5
1
[
2
{name: Food, total: 100},
3
{name: Fuel, total: 30}
4
]
5
What the current code I have, I do not get the output as I want.
JavaScript
1
7
1
const data = this.userData;
2
const groups = data.reduce((groups, item) => ({
3
groups,
4
[item.category]: [ (groups[item.category] || []), item]
5
}), {});
6
console.log(groups);
7
Advertisement
Answer
Try this
JavaScript
1
18
18
1
const userData = [
2
{id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
3
{id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
4
{id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
5
]
6
7
const hashMap = {}
8
9
for (const { category, amount } of userData) {
10
if (hashMap[category]) {
11
hashMap[category].total += amount
12
} else {
13
hashMap[category] = { name: category, total: amount }
14
}
15
}
16
17
const output = Object.values(hashMap)
18
console.log(output)