typescript 如何根据数组项属性对打字稿数组中的值求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52038271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:57:49  来源:igfitidea点击:

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

typescriptmath

提问by Roxy'Pro

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 ReceiptItemlooks :

这是ReceiptItem看起来的样子:

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%"?

我怎样才能在打字稿中获得总金额,但只有在财产税等于“25%”的情况下?

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

在 C# 中,我记得我使用过这样的 lambda 表达式:

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 / Angular 中实现类似的功能?

回答by Suren Srapyan

Arrays in JavaScript/TypeScriptalso have these kind of methods. You can again filterwith you condition and then use reduceaggregation function to sum the items.

JavaScript/TypeScript 中的数组也有这些方法。您可以再次filter使用您的条件,然后使用reduce聚合函数对项目求和。

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

item.tax === '25.00'- 这部分你必须根据你的逻辑进行调整