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>
Author by
Oam Psy
Updated on June 17, 2022Comments
-
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 over 9 yearsProbably the parameter of myAverageFunction should be "MyData", not "data", like "myAveragingFunction(MyData)"
-
RamblerToning over 8 yearsYou're commenting out the closing bracket on the for loop there too
-
James Bell over 8 yearsBut 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 over 8 yearsTypo 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 over 8 yearsSince 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 over 8 yearsWhat about if
MyData.length
is0
? -
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'