我有一个带有时间戳和一些参数的数据集。看起来像这样:
const resp = [
{date: 1576098000, responseBot: 0.47, responseManager: 2.0},
{date: 1576098000, responseBot: 1.50, responseManager: null},
{date: 1576098000, responseBot: 1.05, responseManager: 2.3},
{date: 1576108800, responseBot: 1.00, responseManager: 3.3},
{date: 1576108800, responseBot: 0.60, responseManager: 1.5},
]
...
我需要得到一个分组的结果(按日期)并计算平均响应(机器人和管理者)。预期结果:
[
{date: 1576098000, responseBotAvg: 1.006, responseManagerAvg: 2.15},
{date: 1576108800, responseBotAvg: 0.8, responseManagerAvg: 2.4}
]
在纯JavaScript中达到此结果的最佳方法是什么?
答案 0 :(得分:1)
第一步是使用date
方法和reduce
结合使用concat
键对数组进行分组。
然后只需将average
除以元素的 number 即可找出total sum
。
const resp = [
{date: 1576098000, responseBot: 0.47, responseManager: 2.0},
{date: 1576098000, responseBot: 1.50, responseManager: null},
{date: 1576098000, responseBot: 1.05, responseManager: 2.3},
{date: 1576108800, responseBot: 1.00, responseManager: 3.3},
{date: 1576108800, responseBot: 0.60, responseManager: 1.5},
]
var result = resp.reduce(function(h, obj) {
h[obj.date] = (h[obj.date] || []).concat(obj);
return h;
}, {});
result = Object.keys(result).map(key => {
return {
date: key,
responseBotAvg : result[key].reduce((a, b) => a + (b.responseBot || 0), 0)/result[key].length,
responseManagerAvg : result[key].reduce((a, b) => a + (b.responseManager || 0), 0)/result[key].map(({responseManager}) => responseManager).filter(Boolean).length,
}
});
console.log(result);