0

I have an array of objects that contain a quantity field. I'm looking to total one field from the array on a review screen on a table.

I have an array of administrations populated with object fields and the one I'm looking to calculate is the 'quantity field'.

<tr class="primary" *ngFor="let medication of sachets">
    <td>{{medication.administration.quantity}}</td>
    <td>
        {{medication.medicationName}}
        <p class="instructions">{{medication.additionalInstructions}}</p>
    </td>
</tr>

Within the table, I am calculating the length of entries using angulars .length

I'm looking to calculate a total for the array of quantities.

Reza Heidari
  • 1,192
  • 2
  • 18
  • 23
DZF
  • 137
  • 11
  • You'll need a function that accesses each quantity and sums them up. Here's a native JS example: [Patrick Leib's answer](https://stackoverflow.com/a/63681334/14956277) to [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array). This function can either be in your component code or directly in your template. – D M May 05 '22 at 15:11
  • 1
    So what's the problem you're running into? If you're trying to do the total in the template, I'd suggest setting a property with the total in the component code instead and binding that to the template so you're not looping through the array on each digest cycle. – adam0101 May 05 '22 at 15:12
  • You could also implement a pipe https://stackoverflow.com/questions/42164896/angular-2-pipe-calculating-summary-of-array-of-objects – nll_ptr May 05 '22 at 15:17
  • @adam0101 the issue is looping through each quantity field to total it, the field is within an array of objects and I'm just looking to calculate the total of them. – DZF May 06 '22 at 11:18

1 Answers1

1

Found a solution to filter and add the values. I used the .map function to create an array of quantity values, and using .reduce, add them together to give the desired total.

totalFunction() {
  const initialValue = 0;
  this.totalQuantity = this.administered.map
  (item => item.administration.quantity).reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue);
  console.log(this.totalQuantity);
}
DZF
  • 137
  • 11