# Aggregate for max eviation from average

Hi
I would like to have an aggregate method that returns the most extreme value. That means that the biggest eviation from the average value in the window.

So if I have 10 values [1,2,3,2,8,5,-10,3,5,6] I want -10. I tried to to it with reduce, but I cannot wrap my head around on how I get the average first and then having a conditional update.

My idea was something like this:
extreme: if math.abs(r.avg - r._value) > accumulator.extreme then math.abs(r.avg - r._value) else accumulator.extreme

but it feels also ver inperformant. But dont know what possibilities I have inside the recude and also dont know how to get the average first and add it like a column to every value in that window.

is there a good solution to this without querying all data twice or even multiple times?

Thank you

garcipat

I came up with this now, but the function is somehow not correct defined:

``````import "math"

maxAbs = (a, b) => if math.abs(x: a) > math.abs(x: b) then a else b

from(bucket: "SmartWebUI")
|> range(start: 2022-03-18T08:00:00Z, stop: 2022-03-18T08:01:00Z)
|> filter(fn: (r) => r["_measurement"] == "measurement")
|> filter(fn: (r) => r["_field"] == "Example")
|> mean(column: "_value")
|> reduce(fn: (r, accumulator) => ({
extreme: maxAbs(a: r._avg - r._value, b: accumulator.extreme)
}), identity: { extreme : 0.0 })
|> yield(name: "abc")
``````