Currently, I'm in the process of aggregating three totals: totalPoints
, monthlyTotals
, and monthlyByType
by utilizing Array.prototype.reduce
.
So far, I've managed to successfully calculate totalPoints
and monthlyTotals
, but I'm encountering difficulties with the last one, monthlyByType
.
Below is the array that requires iteration:
const gamePointsArray = [
{
gamePlayId: 'ggg1',
gameType: 1,
gameMonth: 4,
gamePoints: 4000,
},
{
gamePlayId: 'ggg2',
gameType: 2,
gameMonth: 2,
gamePoints: 7000,
},
{
gamePlayId: 'ggg3',
gameType: 2,
gameMonth: 0,
gamePoints: 3000,
},
{
gamePlayId: 'ggg4',
gameType: 1,
gameMonth: 8,
gamePoints: 25000,
},
{
gamePlayId: 'ggg5',
gameType: 3,
gameMonth: 8,
gamePoints: 5000,
},
{
gamePlayId: 'ggg6',
gameType: 3,
gameMonth: 3,
gamePoints: 10000,
},
{
gamePlayId: 'ggg7',
gameType: 2,
gameMonth: 3,
gamePoints: 5000,
},
]
Here's the reducer code snippet:
const gamePointsReducer = (acc, game) => {
const { gamePlayId, gameType, gameMonth, gamePoints,} = game
if (!acc['totalPoints']) {
acc['totalPoints'] = gamePoints
} else {
acc['totalPoints'] += gamePoints
}
if (!acc['monthlyTotals']) {
acc['monthlyTotals'] = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
9: 0,
10: 0,
11: 0,
}
}
acc.monthlyTotals[`${gameMonth}`] += gamePoints
if (!acc['monthByType']) {
acc['monthByType'] = {
0: {},
1: {},
2: {},
3: {},
4: {},
5: {},
6: {},
7: {},
8: {},
9: {},
10: {},
11: {},
}
}
acc.monthByType[`${gameMonth}`] += {
[`${gameType}`]: gamePoints
}
return acc
}
const monthTotalsObj = gamePointsArray.reduce(gamePointsReducer, {})
console.log('Game Points totals obj', monthTotalsObj);
In the end, I would like the resulting Object
to resemble the following structure:
{
totalPoints: 59000,
monthlyTotals: {
0: 3000,
1: 0,
2: 7000,
3: 15000,
4: 4000,
5: 0,
6: 0,
7: 0,
8: 30000,
9: 0,
10: 0,
11: 0,
},
monthByType: {
0: {
2: 3000,
},
1: {},
2: {
2: 7000,
},
3: {},
4: {
1: 4000,
},
5: {},
6: {},
7: {},
8: {
1: 25000,
3: 5000,
},
9: {},
10: {},
11: {},
}
}