I have an array such as this:
[
{
id: 1,
amount: 100
},
{
id: 2,
amount: -50
},
{
id: 3,
amount: 30
}
]
How can I retrieve an array where the amount would be the sum of the previous index sum? For example if the starting amount is 0, I would like to retrieve this array:
[100, 50, 80] // 0 + 100 = 100, then 100 - 50 = 50, then 50 + 30 = 80
You could use accumulator param from the reduce with index - 1 to get the latest value added.
const data = [{"id":1,"amount":100},{"id":2,"amount":-50},{"id":3,"amount":30}]
const result = data.reduce((r, { amount }, i) => {
r.push((r[i - 1] || 0) + amount)
return r
}, [])
console.log(result)
You can also use map and thisArg argument.
const data = [{"id":1,"amount":100},{"id":2,"amount":-50},{"id":3,"amount":30}]
const result = data.map(function({ amount }, i) {
return (this.last = (this.last || 0) + amount)
}, {})
console.log(result)