我试图弄清楚如何获得每天的平均价格。
const groupByDay = _.groupBy(nextProps.data, (date) => {
return moment.unix(date.createdAt).startOf("day").format();
});
const result = _.map(groupByDay, (group, day) => {
return {
date: day.split("T")[0],
offers: group // all offers for the day
}
});
const temp = [];
result.forEach((res) => {
res.offers.forEach((rr) => {
temp.push({date: res.date, avgPrice: rr.price});
})
});
这将返回以下temp
数组,如下所示:
[
{
"date":"2020-01-07",
"avgPrice":334
},
{
"date":"2020-01-07",
"avgPrice":756
},
{
"date":"2020-01-02",
"avgPrice":30
}
]
但是,如何使它分组,然后计算具有相同date
值的所有对象的平均价格?EGavgPrice
的2020-01-07
应该545
是((334+756)/2)
。
无需创建日期价格条目的数组(您只需要再次将它们组合在一起即可!),您可以知道您已经具有一个包含日期的条目列表以及该日期的所有价格。您需要做的是,对于每个条目,将价格数组转换为一个平均价格。一个非常简单的操作Array#reduce
:
//example result value for display purposes
const result = [
{ date: "2020-01-07", offers: [334, 756] },
{ date: "2020-01-02", offers: [30] }
];
//important part, should work with your result array
let temp = result.map((res) => {
return {
date: res.date,
avgPrice: res.offers.reduce((avg, price) => avg + price / res.offers.length, 0)
};
});
console.log(temp);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句