javascript - 查找对象数组中每个索引的平均值?
问题描述
我的大脑正在融化……我正在努力完成以下工作:
我有一个对象数组,其中也有数组:
const data = [
{
seatChartResults: {
'10th': [40, 40, 40, 39, 39, 38, 38, 38, 38, 38],
'90th': [44, 44, 44, 45, 45, 46, 46, 46, 47, 47],
avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
}
},
{
seatChartResults: {
'10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
'90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
}
},
]
现在我想实现一些能够获得这些键的每个索引的平均值的东西,例如:
(data[0].seatChartResults['10th'][0] + data[1].seatChartResults['10th'][0]) / 2
等等 ...
最终结果是将对象聚合到相同的结构中:
{ // With all averages aggregated
seatChartResults: {
'10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
'90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
avg: [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
}
},
这就是我现在所拥有的:
const avgSeatChartResults = (allLambdas) => {
return allLambdas.reduce((acc, { seatChartResults }) => {
Object.keys(seatChartResults).forEach(key => {
const allKeys = [acc.seatChartResults[key] = seatChartResults[key]]
allKeys.map(item => item.reduce((acc, currValue) => acc + currValue, 0) / item.length )
})
return acc
}, { seatChartResults: {} })
}
但是...我不确定这样做是否正确。请帮忙。
解决方案
您可以用来执行此操作的一种方法是:
- 首先计算相应数组的总和并将其收集在地图中(或对象,如果您愿意的话)
- 然后通过计算每个数组中每个条目的平均值进一步将其减少到所需的对象
const data = [{
seatChartResults: {
'10th': [40, 40, 40, 39, 39, 38, 38, 38, 38, 38],
'90th': [44, 44, 44, 45, 45, 46, 46, 46, 47, 47],
'avg': [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
}
},
{
seatChartResults: {
'10th': [41, 40, 40, 39, 39, 39, 38, 38, 38, 38],
'90th': [43, 44, 45, 45, 45, 46, 46, 46, 47, 47],
'avg': [42, 42, 42, 42, 42, 42, 42, 42, 42, 42],
}
},
];
const res = Array.from(data.reduce((acc, {seatChartResults}) => { // add corrsponding array entries
Object.entries(seatChartResults).forEach(([k, arr]) => {
acc.set(k, arr.map((n, i) => ((acc.get(k) || [])[i] || 0) + n));
});
return acc;
}, new Map()).entries())
.reduce((acc, [k, arr]) => { // compute average
acc.seatChartResults[k] = arr.map(n => n / data.length);
return acc;
}, {seatChartResults: {}});
console.log(res);
推荐阅读
- git - 如何解决 git 本地分支跟踪问题?
- python - 无法在 keras 中执行 plot_model
- css - 不使用相邻类中断样式?
- php - 多维表单提交后PHP递归创建db查询:fk字段有时“省略”,但为什么以及如何解决?
- html - 为什么当我给maring auto时,我的按钮显示在彼此下方
- python-3.x - 在网页上查找文本并使用 Python 3 和 BS4 写入文件
- powershell - 使用 Windows 10 Powershell 从文本文件中获取一系列记录
- visual-studio - Visual Studio 2017 包与 netcoreapp2.1 不兼容 NU1202 错误
- flutter - 块水槽被称为空
- vue.js - 边缘和Firefox上的vuetify v-alert错误