{
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)
>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);