I have an array of objects. One of the objects contains an array of objects which holds prices of each item. I want to add them up while mapping. But I am not sure how to do this?
So far I tried to map it this way, but this only renders all the cargoValues per map ( 6092 16485 6879 19980 9516) .. I thought to make a state variable and hold the values in there, however I am guessing that it will return the same value for all of the elements. Which doesn't help me..
<div>
{booking?.pallets.map((pallet: any, i: number) => (
<div key={i}>
{pallet?.cargoValue}
</div>
))}
</div>
Per each iteration ( for example main index 0 ) I would like to add each 'cargoValue' which are: 6092 16485 6879 19980 9516 and then display it as a single value (result of addition). But I'm not sure how to do it this way ?
Anyways, here's an example of such object/array.
0:
pallets: Array(5)
0: {cargoType: 'Engines & spare parts', stackable: false, cargoValue: '6092', count: '2', dangerous: false, …}
1: {cargoType: 'Furniture and accessories/Ceramics', stackable: false, cargoValue: '16485', count: '2', dangerous: false, …}
2: {cargoType: 'Engines & spare parts', stackable: false, cargoValue: '6879', count: '2', dangerous: false, …}
3: {cargoType: 'New Vehicles', stackable: false, cargoValue: '19980', count: '4', dangerous: false, …}
4: {cargoType: 'Industrial products', stackable: false, cargoValue: '9516', count: '2', dangerous: false, …}
length: 5
[[Prototype]]: Array(0)
1:
pallets: Array(4)
0: {cargoType: 'Chemicals & healthcare', stackable: false, cargoValue: '5741', count: '3', dangerous: false, …}
1: {cargoType: 'Old Vehicles', stackable: false, cargoValue: '18877', count: '2', dangerous: false, …}
2: {cargoType: 'Paperboard & prints', stackable: false, cargoValue: '6841', count: '1', dangerous: false, …}
3: {cargoType: 'Chemicals & healthcare', stackable: false, cargoValue: '7558', count: '1', dangerous: false, …}
length: 4
[[Prototype]]: Array(0)
CodePudding user response:
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>
CodePudding user response:
Try this
<div>{booking?.pallets.reduce((val:number, pallet: any) => (
val pallet.cargoValue
)),0}
</div>