Calculate average from list of values in JSON

12,495

I don't think this is related to AngularJS. You need to create a function who calculates your average and then :

<div ng-repeat="data in MyData">
    {{ data.income }}
</div>
<div>
    Average: {{ myAveragingFunction(MyData) }}
</div>
Share:
12,495
Oam Psy
Author by

Oam Psy

Updated on June 17, 2022

Comments

  • Oam Psy
    Oam Psy about 2 years

    I have a simple ng-repeat that displays a list of values (financial income). How can i calculate the average from this list?

    <div ng-repeat="data in MyData">
        {{ data.income }}
    </div>
    <div>
        Average:
    </div>
    

    Which displays:

    11
    14
    8
    9
    21
    10
    2
    1
    5
    13
    

    Thanks

  • agershun
    agershun over 9 years
    Probably the parameter of myAverageFunction should be "MyData", not "data", like "myAveragingFunction(MyData)"
  • RamblerToning
    RamblerToning over 8 years
    You're commenting out the closing bracket on the for loop there too
  • James Bell
    James Bell over 8 years
    But isn't your filter expecting an array when that HTML is sending an integer? And also, isn't the last "data" outside the ng-repeat loop?
  • SirTophamHatt
    SirTophamHatt over 8 years
    Typo in the HTML. Assuming MyData is an array of integers and not a collection of objects, you would ng-repeat over MyData and passed MyData to the average filter. If MyData were a structure like the Controller example, then you'd iterate over MyData.income and output MyData.average outside the ng-repeat block.
  • SirTophamHatt
    SirTophamHatt over 8 years
    Since none of these examples consider that his array is a collection, he's better off changing his structure or writing a function to accept a collection and sum the .income property.
  • tomasbedrich
    tomasbedrich over 8 years
    What about if MyData.length is 0?
  • Matt Westlake
    Matt Westlake over 7 years
    @tomasbedrich if myData.length == 0 then 0 < 0 is false and it will skip the for loop. The problem is when you get to var avg = 0/0 which is 'undefined'