I am trying to calculate the average of values with the same key in a array of objects. Not all the Objects consist of the same values as the other but I still want the average returned depending on how many times it appears in the array. For example I want
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
}]
To return
{
2005: 5.599999999999999,
2006: 5.6000000000000005,
2007: 5.6
}
This is what I have tried so far. Right now the problem is that I have no way to / it by the amount of times it appears. And if it is missing the year the value becomes undefined and this causes the result to be 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)