3

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: ?
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
illy
  • 41
  • 4
  • Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Sebastian Simon Jul 14 '21 at 02:17

1 Answers1

4

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);
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • Hi Spectric, what about if it was an object with objects? – illy Jul 15 '21 at 01:44
  • @illy Depends what you mean. What does the object look like? – Spectric Jul 15 '21 at 01:45
  • Hi Spectric, I edited my original question up above^. Thanks! – illy Jul 15 '21 at 01:50
  • @illy I would recommend posting a new question in this case - it's more organized and efficient than editing a question over and over again. I'll make sure to leave an answer if you do :) – Spectric Jul 15 '21 at 01:52
  • Ok I posted it under https://stackoverflow.com/questions/68386944/self-reference-in-object-literals . Spectric, you are awesome! – illy Jul 15 '21 at 01:58