Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS condition with map and reduce

{
change: "credit"
currency: "EUR"
value: "30.00"
}
{
change: "debit"
currency: "EUR"
value: "15.00"
}

This is working and returning the correct result:

const totalMovements = customerMovements.map(a => parseFloat(a.value).reduce((acc, n) => acc + n)

I want the sum of the values with change === 'credit'. The result should be 30. This is not working when i add the ‘change’ condition, can someone help?:

const totalMovements = customerMovements.map(a => parseFloat(a.value) && a.change === 'credit').reduce((acc, n) => acc + n)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are returning a boolean in your map in the second example, so the array you end up reducing is just an array of booleans. [true, false].reduce(....

It looks like you want to filter() by credit and then sum?

const customerMovements = [{ change: 'credit', currency: 'EUR', value: '30.00', }, { change: 'debit', currency: 'EUR', value: '15.00', },];

const totalMovements = customerMovements
    .map((a) => parseFloat(a.value))
    .reduce((acc, n) => acc + n, 0);

console.log(totalMovements);

const totalCredits = customerMovements
    .filter(({ change }) => change === 'credit')
    .map((a) => parseFloat(a.value))
    .reduce((acc, n) => acc + n, 0);

console.log(totalCredits);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading