Calculate derivative

Hi
how can I do a derivative data wide (not a window aggregation)?
I did something like this but it looks a bit ugly

data = from(bucket: "my bucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r._measurement == "myda")
  |> filter(fn: (r) => r._field == "price")
  |> keep(columns:["_value"])
  
lastt = data |> last() 

firstt = data |> first()
 
mytable = union(tables:[lastt, firstt])
j = mytable 
  |> tableFind(fn: (key) => 1==1)
  |> getColumn(column: "_value")

mytable
  |> map(fn: (r) => ({ r with _value:  (-j[1]+j[0])/j[1]*100.0}))
  |> first()

Thanks

@James1 You could use reduce(). I think I’ve duplicated the logic of your code in here:

data = from(bucket: "my bucket")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r._measurement == "myda")
  |> filter(fn: (r) => r._field == "price")
  |> keep(columns:["_value"])

customFunction = (tables=<-) => 
  tables
    |> reduce(
      identity: {index: 0, first_value: 0.0, _value: 0.0},
      fn: (r, accumulator) => ({
        r with
        index: accumulator.index + 1,
        first_value: if accumulator.index == 0 then r._value else accumulator.first_value,
        _value: if accumulator.index == 0 then 100.0 else (accumulator._value - r._value) / accumulator._value * 100.0
      })
    )
    |> drop(columns: ["index", "first_value"])

data
  |> customFunction()