Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 960
Bea Avatar asked Aug 29 '16 20:08

Bea


1 Answers

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);
}
like image 87
Nitzan Tomer Avatar answered Oct 22 '22 09:10

Nitzan Tomer