我正在尝试计算对象数组中具有相同键值的平均值。 并非所有对象都包含与另一个相同的值,但我仍然希望根据它在数组中出现的次数返回平均值。 比如我要
const Object1 = [{
2005: 5.6,
2006: 5.2
}, {
2005: 5.6,
2006: 5.7,
2007: 5.4
}, {
2005: 5.6,
2006: 5.9,
2007: 5.8
}]
返回
{
2005: 5.599999999999999,
2006: 5.6000000000000005,
2007: 5.6
}
到目前为止,这是我尝试过的。 现在的问题是我无法按它出现的次数来/它。如果缺少年份,则该值将变为未定义,这会导致结果为 NaN。
const Object1 = [{
2005: 5.6,
2006: 5.2
}, {
2005: 5.6,
2006: 5.7,
2007: 5.4
}, {
2005: 5.6,
2006: 5.9,
2007: 5.8
}]
const years = Object.keys(Object.assign({}, ...Object1));
const Result = years.reduce((a, v) => ({
...a,
[v]: v
}), {})
console.log(Result)
years.map((year) => {
const value =
Object1.map(function(obj) {
return obj[year]
}).reduce(function(a, b) {
return (a + b)
}) / years.length
Result[year] = value
})
console.log(Result)
最佳答案
您可以按年对分数进行分组,并单独根据每个组计算分数
const object1 = [
{
2005: 5.6,
2006: 5.2,
},
{
2005: 5.6,
2006: 5.7,
2007: 5.4,
},
{
2005: 5.6,
2006: 5.9,
2007: 5.8,
},
];
const groupPointByYears = object1.reduce((map, obj) => {
for (const [year, point] of Object.entries(obj)) {
if (!map.has(year)) {
map.set(year, []);
}
map.get(year).push(point);
}
return map;
}, new Map());
console.log(Array.from(groupPointByYears));
const res = Object.fromEntries(
Array.from(groupPointByYears).map(([year, points]) => [
year,
points.reduce((sum, point) => sum + point, 0) / points.length,
])
);
console.log(res);
关于javascript - 通过过滤未定义计算对象数组的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71948451/