I am building a dashboard to compare the cumulative spending of the current month against the cumulative spending of the last month. This looks like this:
As you can see below, my code is very naive and I am pretty sure it can be improved. Right now I loop many times over the arrays to fill each date of currentMonthSpend
with the appropriate sum of transactions that happened on this date, cumulated with the previous values ...
Would you be able to guide me with a smarter way of doing it? The current logic is the following:
- Create the array date objects (with
x
= date andy
= cumulative sum) - I already have my list of transactions (with date and amount for each entry which can obviously happen at the same date of another entry)
- First, I iterate through
currentMonthTransactions
, I find the corresponding date incurrentMonthSpend
and I increment they
property - Then I iterate through
currentMonthSpend
and I apply a cumulative sum
Thanks for your help!
const startOfCurrentMonth = moment().startOf("month");
const endOfCurrentMonth = moment().endOf("month");
const currentMonthSpend = [];
while (startOfCurrentMonth.isSameOrBefore(endOfCurrentMonth)) {
currentMonthSpend.push({ x: startOfCurrentMonth.format("YYYY-MM-DD"), y: 0 });
startOfCurrentMonth.add(1, "days");
}
const currentMonthTransactions = [
{
date: "2022-10-03",
amount: -50,
},
{
date: "2022-10-04",
amount: -100,
},
{
date: "2022-10-05",
amount: -20,
},
{
date: "2022-10-05",
amount: -10,
},
{
date: "2022-10-08",
amount: -40,
},
];
for (let i = 0; i < currentMonthTransactions.length; i++) {
let index = currentMonthSpend.findIndex((item) => {
return item.x === currentMonthTransactions[i].date;
});
if (index !== -1) {
currentMonthSpend[index].y += currentMonthTransactions[i].amount;
}
}
const result = currentMonthSpend.map((obj, index, self) => {
if (index == 0) {
obj.y = 0;
return obj;
}
const prevO = self[index - 1];
obj.y += prevO.y;
obj.y = +obj.y.toFixed(2);
return obj;
});
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Comments
Post a Comment