For someone who is looking for array of objects,
Sample array of objects
{
"month": "2020-05",
"start_date": "2020-05-01",
"end_date": "2020-05-31",
"invoices_count": 19,
"total_margin": 44420.83,
"total_revenue": 415826.48999999993
},
{
"month": "2020-10",
"start_date": "2020-10-01",
"end_date": "2020-10-31",
"invoices_count": 25,
"total_margin": 62583.130000000005,
"total_revenue": 553906.81
},
{
"month": "2020-09",
"start_date": "2020-09-01",
"end_date": "2020-09-30",
"invoices_count": 21,
"total_margin": 46459.35,
"total_revenue": 397549.66000000003
}]
The below is the code to get cumulative sum of total_margin for each object
data.map((item, index) =>
index === 0
? item
: {
...data[index],
'total_margin': data
.slice(0, index + 1)
.reduce((prev, curr) => prev + curr[total_margin], 0),
}
);
Expected output:
[
{
"month": "2020-05",
"start_date": "2020-05-01",
"end_date": "2020-05-31",
"invoices_count": 19,
"total_margin": 44420.83,
"total_revenue": 415826.48999999993
},
{
"month": "2020-10",
"start_date": "2020-10-01",
"end_date": "2020-10-31",
"invoices_count": 25,
"total_margin": 107003.96,
"total_revenue": 553906.81
},
{
"month": "2020-09",
"start_date": "2020-09-01",
"end_date": "2020-09-30",
"invoices_count": 21,
"total_margin": 153463.31,
"total_revenue": 397549.66000000003
}]