Adel
Adel

Reputation: 77

How to get the summation of iterated FormArray

I'm having a function where it gathers values from specific input, this input is a part of FormArray within FormGroup (nested), the function is like this

addSales(){

 this.itemsArray.controls.findIndex(i => {

    this.totalPrice =parseFloat(i.get('price').value)

    console.log(this.totalPrice)

}
  )}

when adding multiple values like : 10,20,30 I get them printed like this

10
20
30

All what I need is returning the sum of these values, which is 60, would you please advise me how to do it

Upvotes: 1

Views: 39

Answers (2)

TheScrappyDev
TheScrappyDev

Reputation: 4963

From a philosophical perspective, there's a few things I'd recommend changing about the code:

  1. follow a functional paradigm (no side effects)

  2. use reduce instead of findIndex for generating a new value from iterating over an array (see reduce docs)

Right now the addSales function is performing two roles: (1) iterating through itemsArray and (2) updating this.totalPrice for each item in itemsArray. It makes the code harder to test because there's a lot going on.

Instead, I'd recommend doing the following:

addSales(): number {
  return this.itemsArray.controls.reduce((sum, i) => {
    sum += parseFloat(i.get('price').value)
    return sum;
  }, 0);
}

handleInputChange() {
  this.totalPrice = this.addSales();
}

Once handleInputChange is bound to your input change in the template, you will be able to more easily see what the code is doing (thereby debugging it easily).

Upvotes: 1

ehutchllew
ehutchllew

Reputation: 958

+= instead of = after this.totalPrice

Upvotes: 0

Related Questions