93

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?

1 Answer 1

183

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

Sign up to request clarification or add additional context in comments.

5 Comments

what does this line means? reduce((sum, current) => sum + current.total, 0);
reduce is an aggregation function like Aggregate in C#. It gets an total an every item in the iteration and in this case we sum each item's total to the total (sum) and finally get the sum
@Roxy'Pro: there's no direct JavaScript equivalent to Sum() LINQ function. But Sum() can be written using Aggregate().
I like splitting operation like you do : filter then sum with reduce.
@roxypro: Notice that, as filter produces an intermediate array, in case receiptItems contains a lots of items, the filtering part can be done directly in the reduce : receiptItems.reduce((sum, x) => sum + (x.tax === '25.00' ? x.total : 0));

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.