[英]Reduce with condition in array js
i'm facing a problem with filter and reduce.我面临过滤和减少的问题。 I need to get the sum of "smc" only when "A" is equal 2020. This is my array:只有当“A”等于 2020 时,我才需要得到“smc”的总和。这是我的数组:
arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}]
I've tried something like:我试过类似的东西:
arr.filter(e=> e.A===2020).reduce((sum, iter) => sum + iter.smc)
but it doesn't seem to work.但它似乎不起作用。 Any ideas why?任何想法为什么? Thank you谢谢
You need to pass second argument as 0
to reduce()
which becomes the initial value of sum
.您需要将第二个参数作为0
传递给reduce()
,这将成为sum
的初始值。
arr.filter(e=> e.A===2020).reduce((sum, iter) => sum + iter.smc, 0)
You can also remove filter()
use reduce()
only with ternary operator您还可以删除filter()
使用reduce()
仅与三元运算符
const arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}]; let res = arr.reduce((ac, {smc, A}) => ac + (A === 2020? smc: 0), 0); console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.