Average from an array

I have looked through the documentation, but have not found an easier way to find the average of all of the elements of an array other than looping through the array to create the sum, then dividing by the number of elements in the array. I know how to do that, but I was wondering if there is there an easier way? Coming from VB, sometimes I miss the smallest things simply because they are named differently in Xojo.

Thanks in advance!

Loop through the array, sum it up, and divide by the number of elements. That’s pretty simple all by itself. No other shortcut that I’m aware of.

one option so you can use it with every array that have currency values

test

[code]Var a(-1) As Currency
a.AddRow(10.5)
a.AddRow(14.2)

System.DebugLog(Str(a.Sum))

System.DebugLog(Str(a.Average))
[/code]

global method in module

[code]Public Function Sum(Extends Data() As Currency) as Currency
Var sum As Currency = 0.0

For Each c As Currency In Data
sum = sum + c
Next

Return sum

End Function
[/code]

[code]Public Function Average(Extends Data() As Currency) as Currency
Var sum As Currency = 0.0
Var count As Currency = 0.0

If Data.Count = 0 Then Return 0.0

For Each c As Currency In Data
sum = sum + c
count = count + 1.0
Next

Return sum / count

End Function
[/code]

Correct Markus, but with you functions you could write average as:

Public Function Average(Extends Data() As Currency) as Currency
  If Data.Count = 0 Then Return 0.0
  
  Return Data.Sum/Data.Count
End Function

Simpler and faster

great shortcut :slight_smile: