11

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

1 Answer 1

29

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I know this is old, but couldn't you just to this.creancesOfSelectedRemise = this.creances.reduce((sum, c) => sum + c.creance_montant, 0);?
@Jocie The OP wanted to filter out some elements from the list (based on remise.id_remettant). Your solution doesn't seem to take that into account.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.