I am currently working with the Angular JS framework and have a NodeJS array like this:
var arr = [{"object":"Anguille","fct":"Type A","value":"2"},{"object":"Athérine","fct":"Type A","value":"1.0031643586595139"}, {"object":"Epinoche","fct":"Type B","value":"1"}, {"object":"Mulet ","fct":"Type B","value":"5"}];
I am trying to calculate the mean of the "value" grouped by each "fct" as follows:
{ 'Type A': 1.5, 'Type B': 3 }
So far, I have managed to group the values but only using sum
and not mean
. I believe I need to use the arr.reduce
function but I am unsure about how to implement it in my code.
This is the snippet I have tried:
const obj = {};
arr.forEach((item) => {
obj[item.fct] = obj[item.fct] ? obj[item.fct] +
parseInt(item.value) : parseInt(item.value);
});
console.log(obj);
I seem to be stuck at this point. Can you suggest a way to modify my snippet to calculate the mean instead of the sum?
Any guidance or help on this would be highly appreciated. Thank you.