Reduce with condition in array js

Viewed 365

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:

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

1 Answers

You need to pass second argument as 0 to reduce() which becomes the initial value of 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

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)

Related