Origin Object is:
obj = { date: '2021-05-30', stock: 230, location_id: 'Bangalore' },
{ date: '2021-05-31', stock: 350, location_id: 'Bangalore' },
{ date: '2021-06-01', stock: 320, location_id: 'Bangalore' },
{ date: '2021-06-07', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-08', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-09', stock: 210, location_id: 'Bangalore' },
{ date: '2021-06-10', stock: 210, location_id: 'Bangalore' },
]
obj.reduce((m, o, i) => {
var prev = m[i - 1];
if (prev) {
o.stock = o.stock + prev.stock;
}
m.push(o);
return m;
}, []);
I tried above script but is updating current date itself. But I am getting following outcome:
0: {date: "2021-05-31", stock: 230, location_id: "Bangalore"}
1: {date: "2021-05-31", stock: 580, location_id: "Bangalore"}
2: {date: "2021-06-01", stock: 900, location_id: "Bangalore"}
3: {date: "2021-06-07", stock: 1110, location_id: "Bangalore"}
4: {date: "2021-06-08", stock: 1320, location_id: "Bangalore"}
5: {date: "2021-06-09", stock: 1530, location_id: "Bangalore"}
6: {date: "2021-06-10", stock: 1740, location_id: "Bangalore"}```
Expecting format is like
0: {date: "2021-05-30", stock: 0, location_id: "Bangalore"}
1: {date: "2021-05-31", stock: 230, location_id: "Bangalore"}
2: {date: "2021-06-01", stock: 580, location_id: "Bangalore"}
3: {date: "2021-06-07", stock: 900, location_id: "Bangalore"}
4: {date: "2021-06-08", stock: 1110, location_id: "Bangalore"}
5: {date: "2021-06-09", stock: 1320, location_id: "Bangalore"}
6: {date: "2021-06-10", stock: 1530, location_id: "Bangalore"}```
Please anyone provide the right solution is greatly appreciated!