简体   繁体   中英

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:

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. What is the proper and simplest way to do this with the reduce() function? 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?:

let grandTotalsFooter = {};
grandTotalsFooter.TotalOfMaterial = commodityDeliveries.sum(x => x.Total);

The .NET sum() function is much more straightforward and intuitive. I would think that the JS standards would introduce a sum() function like this at some point?

The function passed to reduce must take two parameters (or more): an accumulator, and the current item. So your assignment becomes:

grandTotalsFooter.TotalOfMaterial = commodityDeliveries.reduce((acc, item) => acc+item.Total);

See the MDN for more details on Array.prototype.reduce() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM