I want to find average of an array of objects based on their key values using the new functional programming style. I found my way around array reduce
and solved my problem, but not sure if this is the best way to do it.
Please take a look at my code and see if this is the way to use reduce for my purpose.
Let's say I have an array of objects as follows:
private data = [
{tv: 1, radio:5,fridge:4},
{tv: 2, radio:2,fridge:null},
{tv: 3, radio:6,fridge:5}
];
I want to create another array containing the averages of each of the items in my data array. What I have, and is working, is below:
function summary(){
var keys= Object.keys(data[0]);
var sums = {};
var averages = Object.keys(this.data.reduce((previous, element) => {
keys.forEach(el => {
if(element[el] !== null){
if (previous.hasOwnProperty(el)) {
previous[el].value += element[el];
previous[el].count += 1;
} else {
previous[el] = {
value: element[el],
count: 1
};
}
}
});
return previous;
}, sums)).map(name => {
return {
name: name,
average: sums[name].value / sums[name].count
};
});
console.log(averages);
}
Running the code will give me my expected results:
average = [
{ "name": "tv", "average": 2 },
{ "name": "radio", "average": 4.333333333333333 },
{ "name": "fridge", "average": 4.5 }
]
But is this the best way to solve my problem using new reduce
functions?