# 这个如何改成reduce的写法？

3131975015
• 546
``````let total = 0
this.data.list2.map(res=>{
if(res.checked){
total+=res.money
}
})``````

`let sum = this.data.list2.reduce((pre,next)=>pre.checked?pre.money+next.money:'')`

4 个回答
``````// 1. 在 reduce 过程中来加
const total = this.data.list2.reduce(
(total, it) => total + (it.checked ? it.money : 0), // 按条件累加
0       // 累加初始值为 0
);``````
``````// 2. 先过滤，再累加
const total = this.data
.filter(({ checked }) => checked)
.reduce(
(total, { money }) => total + money,
0
);``````
``````// 3. 过滤，映射，再累加
const total = this.data
.filter(({ checked }) => checked)
.map(({ money }) => money)
.reduce((total, money) => total + money);   // total 和 money 类型相同，可以不要初始值``````

``````const total = _(this.data)
.filter(({ checked }) => checked)
.map(({ money }) => money)
.reduce((total, money) => total + money);``````
ForkKILLET
• 2.5k
``this.data.list2.reduce((acc, cur) => acc + cur.money * cur.checked, 0)``

``const total = this.data.list2.reduce((result,current) => pre.checked ? (result + pre.money) : result, 0)``
``let sum = this.data.list2.reduce((pre, next) => (next.checked && (pre += next.money), pre), 0)``

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进