在数组中进行映射时返回上一个和当前的索引和



我有一个这样的数组:

[
{
id: 1,
amount: 100
},
{
id: 2,
amount: -50
},
{
id: 3,
amount: 30
}
]

如何检索一个数组,其中的数量将是上一个索引和的总和?例如,如果起始数量是0,我想检索这个数组:

[100, 50, 80] // 0 + 100 = 100, then 100 - 50 = 50, then 50 + 30 = 80

您可以使用reduceindex - 1的累加器参数来获得最新添加的值。

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)

您也可以使用mapthisArg参数。

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)

最新更新