New in TypeScript — Angular 2.
I wondering to know how to calculate a sum from a list.
I already selected the items needed and get the sum with a error :
TS Error Type 'void' is not assignable to type 'Creance[]',
creancesOfSelectedRemise: Creance[];
onSelectRemise(remise: Remise, event: any) {
...//...
this.creancesOfSelectedRemise = this.creances
.filter(c => c.id_remettant === remise.id_remettant)
.forEach(c => this.totalCreances += c.creance_montant);
}
It seems 'forEach' is not used correctly.
Is it possible to add the filter and the forEach in the same time ?
thanks Bea
Instead of using forEach you should use map to return the numbers you want to sum up, and then use reduce to sum them:
onSelectRemise(remise: Remise, event: any) {
...
this.creancesOfSelectedRemise = this.creances
.filter(c => c.id_remettant === remise.id_remettant)
.map(c => c.creance_montant)
.reduce((sum, current) => sum + current);
}
You can remove a cycle of iterations by filtering out the items in the mapping:
onSelectRemise(remise: Remise, event: any) {
...
this.creancesOfSelectedRemise = this.creances
.map(c => c.id_remettant === remise.id_remettant ? c.creance_montant : 0)
.reduce((sum, current) => sum + current);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With