How to calculate the amount from a list - Typescript - Angular2

New in TypeScript - Angular 2.

I am interested to know how to calculate the amount from the list.

I have already selected the necessary items and get the amount with an error:

Error type TS "void" is not assigned 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 that "forEach" is being used incorrectly.

Can I add a filter and a forEach value at the same time?

thanks beah

+4
source share
1 answer

Instead of forEach, you should use map to return the numbers you want to sum, 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);
}

, :

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

Source: https://habr.com/ru/post/1652918/


All Articles