Home > Blockchain >  How to calculate the average value of the properties of an object?
How to calculate the average value of the properties of an object?

Time:11-30

Tell me please. How to calculate the average value of the properties of an object?

I have object.

const components {
    “co”: 235, 465, 78,
    “no” 409, 589, 98,
    “nh3”: 54, 76,39
}


I need to separately calculate the average for "co", "no", and "nh3".

Please tell me the solution. My attempts result in NaN

CodePudding user response:

  1. Have a proper object
  2. you can use reduce/length

I use a trick to shorten the decimals, toFixed with a unary plus to convert back to number

There are more tricks here. The object.assign converts the array of object to one object

const components = {
  "co": [235, 465, 78],
  "no": [409, 589, 98],
  "nh3": [54, 76, 39]
}

const avgs = Object.assign({}, ...Object.entries(components).map(([key,values]) => (
  {[key]: (values.reduce((a,b)=>a b)/values.length).toFixed(2)}
)))
console.log(avgs)

CodePudding user response:

I have corrected your invalid object and tried to get the average values in an array:

let components = {
  co: [235, 465, 78],
  no: [409, 589, 98],
  nh3: [54, 76, 39]
};

let result = [];
Object.keys(components).forEach(function (key) {
  avg = components[key].reduce((a, b) => a   b, 0) / components[key].length;
  result.push(avg);
});

console.log(result);

CodePudding user response:

You could get the entries and build a new object with averages.

const
    getAverage = array => array.reduce((a, b) => a   b) / array.length,
    components = { co: [235, 465, 78], no: [409, 589, 98], nh3: [54, 76, 39] },
    result = Object.fromEntries(Object
        .entries(components)
        .map(([k, v]) => [k, getAverage(v)])
    );
    
console.log(result);

  • Related