gpt4 book ai didi

javascript - lodash、分组和计数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:24:38 24 4
gpt4 key购买 nike

像这样的数组

[{ dep: 'A', qt: 10, price: 5},
{ dep: 'A', qt: 5, price: 2.30 },
{ dep: 'B', qt: 3, price: 2.20 },
{ dep: 'C', qt: 1, price: 4 },
{ dep: 'C', qt: 4, price: 10 }
...etc..
]

什么是对值进行分组和求和的优雅方法,结果是:

[{ dep: 'A', qt: 15, price: 61.5 },
{ dep: 'B', qt: 3, price: 2.20 },
{ dep: 'C', qt: 5: price: 44 }
]

最佳答案

你可以这样做:

function sumInvoices(p, c) {
return _.extend(p, {qt:p.qt + c.qt, price:p.price + c.qt*c.price});
};

var b = _(a)
.groupBy('dep')
.map(function(b) {return b.reduce(sumInvoices, {dep:b[0].dep, qt:0, price:0})})
.valueOf();

关于javascript - lodash、分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com