How to perform addition for each mapping iteration

Viewed 33

EDIT: deleted due to qustion being outdated

2 Answers

You can use .reduce((accumulator, item) -> newAccumulator, initialValue) to calculate the sum of your items.

For your pallets you could get it like this

const sum = pallets.reduce((acc, pallet) => acc + (+pallet.cargoValue), 0)

Because your cargoValue is a string, you have to convert it to a number with +pallet.cargoValue before you add it to the accumulator acc, otherwise it will perform a string concatenation instead of a number addition.

<div>
    {booking?.pallets.reduce((acc, pallet) => acc + (+pallet.cargoValue), 0)}
</div>

Try this

<div>{booking?.pallets.reduce((val:number,       pallet: any) => (
         val + pallet.cargoValue
        )),0}
</div>
Related