Javascript Average of Array of Objects property

Viewed 35

Im stuck on how I would go about writing this calculation out. Basically. I have an array of objects and I need to know the average level achieved (incentive_level). I believe in this case it is 0

[
  {incentive_level: 0, users: 183},
  {incentive_level: 1, users: 72},
  {incentive_level: 2, users: 57},
  {incentive_level: 3, users: 9}
]
1 Answers

Loop through the records, keeping track of total # of users and cumulative score, then do the division at the end. Something like:

var list = [
  {incentive_level: 0, users: 183},
  {incentive_level: 1, users: 72},
  {incentive_level: 2, users: 57},
  {incentive_level: 3, users: 9}
]

var totalUsers = 0
var totalScore = 0

for(var i=0; i< list.length;i++){
  totalUsers += list[i].users
  totalScore += (list[i].users * list[i].incentive_level)
}

console.log("Total Users: " + totalUsers)
console.log("Total Score: " + totalScore)

var average = totalScore/totalUsers

console.log(average)

Related