有一组数据如下:
const data = [
{ "序号": 1, "取样时间": "2020-03-10", "cq": "3cq","cj": "8cj","pc": "3pc","sf": 42.381,pH: 5.524,"atd": 334.922},
{ "序号": 2, "取样时间": "2020-03-10", "cq": "3cq","cj": "8cj","pc": "3pc","sf": 45.31,pH: 5.624,"atd": 337.222},
{ "序号": 1, "取样时间": "2020-03-14", "cq": "3cq","cj": "7cj","pc": "3pc","sf": 41.37,pH: 5.504,"atd": 330.922},
{ "序号": 1, "取样时间": "2020-03-15", "cq": "1cq","cj": "7cj","pc": "1pc","sf": 40.37,pH: 5.204,"atd": 380.922},
];
求这组数据两个相同key,其他数据的平均值
//计算数组平均值
function averagedata(arr,str) {
var data = arr.reduce((acc, val) => acc + val[str], 0)/arr.length;
return data
}
// 使用reduce函数对数组进行处理,初始累加器(acc)为空对象{}
function groupBy(arr,str) {
const dataBytime = arr.reduce((acc, arrdata) => {
// 获取当前数据两个key
const keysdata = `${arrdata.取样时间}|${arrdata[str]}`; //第一个key是取样时间,另一个就是其他的,可以是cq,cj等
console.log(keysdata)
// 检查acc对象中是否已经存在以当前两个为键的数组
if (!acc[keysdata]) {
// 如果不存在,创建一个空数组
acc[keysdata] = [];
}
// 将当前数据添加到对应数组中
acc[keysdata].push(arrdata);
// 返回更新后的累加器对象
return acc;
}, {}); // 初始累加器为空对象
var datasjn = [];
for (i in dataBytime) {
console.log(dataBytime[i])
if (dataBytime[i].length>1) {
var p = {"取样时间":dataBytime[i][0].取样时间,[str]: dataBytime[i][0][str],"sf":averagedata(dataBytime[i],'sf'),pH:averagedata(dataBytime[i],'pH'),"atd":averagedata(dataBytime[i],'atd')}
datasjn.push(p)
}
else {
var p = {"取样时间":dataBytime[i][0].取样时间,[str]: dataBytime[i][0][str],"sf":dataBytime[i][0].sf,pH:dataBytime[i][0].pH,"atd":dataBytime[i][0].atd}
datasjn.push(p)
}
}
return datasjn
}
console.log(groupBy(data,'pc'))