[英]what is the proper way to implement this routine with reduce() function?
I'm trying to sum all of the Total values in a commodityDeliveries array into a TotalOfMaterial property as shown below:我正在尝试将商品交付数组中的所有 Total 值汇总到 TotalOfMaterial 属性中,如下所示:
let grandTotalsFooter = {};
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.reduce(x => x.Total);
I know that a proper reduce() implementation is not as simple as what I have above but just providing the general intent of what I'm trying to do.我知道一个适当的 reduce() 实现并不像我上面的那么简单,而只是提供我想要做的事情的一般意图。 What is the proper and simplest way to do this with the reduce() function?使用 reduce() 函数执行此操作的正确且最简单的方法是什么? Also, is there a popular third-party js lib which simplifies this kind of routine with a sum() function similar to the .NET framework as follows?:另外,是否有一个流行的第三方 js 库,它使用类似于 .NET 框架的 sum() 函数简化了这种例程,如下所示?:
let grandTotalsFooter = {};
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.sum(x => x.Total);
The .NET sum() function is much more straightforward and intuitive. .NET sum() 函数更加直接和直观。 I would think that the JS standards would introduce a sum() function like this at some point?我认为 JS 标准会在某个时候引入这样的 sum() 函数?
The function passed to reduce
must take two parameters (or more): an accumulator, and the current item.传递给reduce
的函数必须接受两个(或更多)参数:一个累加器和当前项。 So your assignment becomes:所以你的任务变成:
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.reduce((acc, item) => acc+item.Total);
See the MDN for more details on Array.prototype.reduce()
. 有关Array.prototype.reduce()
更多详细信息,请参阅 MDN 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.