2

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 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.