Bea Bea - 3 months ago 36
TypeScript Question

How to calculate sum from a list — Typescript - Angular2

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

Answer

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