How to sum values in typescript array based on array items property?

TypescriptMath

Typescript Problem Overview


I'm working on small angular project. I have an array of receipt items, e.g. coke, fanta, pepsi, juice etc, with their prices and quantity of course.

receiptItems: Array<ReceiptItem>;

This is how ReceiptItem looks :

export class ReceiptItem {

  public id: string;
  public product: Product;
  public unitOfMeasure: UnitOfMeasure;
  public discount: number;
  public price: number;
  public quantity: number;
  public total: number;
  public tax:Tax;

 }

How can I in typescript get sum of total amount but only where property tax for example is equal to "25%"?

In C# I remember I've used lambda expressions like this:

IEnumerable<ReceiptItems> results = receiptItems.Where(s => s.Tax == "25.00");
   totalSum = results.Sum(x => (x.TotalAmount));

How to achieve something similar in TypeScript / Angular?

Typescript Solutions


Solution 1 - Typescript

Arrays in JavaScript/TypeScript also have these kind of methods. You can again filter with you condition and then use reduce aggregation function to sum the items.

const sum = receiptItems.filter(item => item.tax === '25.00')
                        .reduce((sum, current) => sum + current.total, 0);

item.tax === '25.00' - this part you must adjust with your logic

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoxy&#39;ProView Question on Stackoverflow
Solution 1 - TypescriptSuren SrapyanView Answer on Stackoverflow