illy
illy

Reputation: 41

find the average between object values to use as a value for another object key in Javascript

How do I find the average between the scores of the 2 games all within the same object?

var scores = {
   game1 : 55,
   game2 : 62,
   average: ?
}

Upvotes: 3

Views: 301

Answers (1)

Spectric
Spectric

Reputation: 31992

If the number of games is fixed, you can do very simply:

var scores = {
  game1: 55,
  game2: 62,
}
scores.average = (scores.game1 + scores.game2) / 2;
console.log(scores);

If the number of games isn't fixed, you can loop through the properties of the object and add each value to an array, then calculate the sum of the array and divide by its length to get the average.

var scores = { game1 : 55, game2 : 62}
var scoreArr = [];
for(const a in scores){
  scoreArr.push(scores[a]);
}
scores.average = scoreArr.reduce((a, b) => a + b, 0) / scoreArr.length;
console.log(scores);

Upvotes: 4

Related Questions