user10354541
user10354541

Reputation:

Calculate Average of JSON Values

I am trying to calculate the average of JSON values, I tried to add them to an array but not able to. Can someone please help?

My code:

Object.values(data).forEach(d => {
  var yo = d.values;
  console.log(yo);
});

My results:

9892308
9894522
3298714
3300055

I need to calculate the average of these values. How do I do that?

Code to push values in an array:

Object.values(data).forEach(d => {
  var theArray = [];
  var yo = d.values;
  theArray = theArray.push(yo);
  console.log(theArray);
});

Result:

  1

I am not able to push the values for me to calculate the array.

Upvotes: 0

Views: 7316

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386736

You could reduce the data by taking the nth (length) of the value and add it to the average in a single loop.

var data = { a: { values: 9892308 }, b: { values: 9894522 }, c: { values: 3298714 }, d: { values: 3300055 } },
    average = Object
        .values(data)
        .reduce((avg, { values }, _, { length }) => avg + values / length, 0);
        
console.log(average);

Upvotes: 1

Hodrobond
Hodrobond

Reputation: 1696

Depends how you have your data structured, but an Array.reduce should get you the sum, and divide by the length for the average.

const data = {
  a: {
    values: 9892308,
  },
  b: {
    values: 9894522,
  },
  c: {
    values: 3298714,
  },
  something_weird: {
    values: 3300055,
  }
}





const sum = Object.values(data).reduce((acc, current) => acc + current.values, 0);

const average = sum / Object.values(data).length;
console.log(average);

Upvotes: 0

Related Questions