Typescript function to find average difference between timestamps

I have an object with two timestamp properties (timestampOpen and timestampClose). I want to find the average difference between the two (average of all (timestampClose - timestampOpen). Is this possible using the Typescript object aggregation functions? Ideally, I do not want to convert the object set to a list and then calculate the average using native Typescript functions.

Hey there @apeng ,

I don’t think this is currently possible by calling the average directly on a .groupBy() / .segmentBy() statement.

The closest I’ve been able to get is doing something like this (all placeholder variables / parameters):

    const ObjectsToGetAvgTimestampDiff = await Objects
        .search()
        .yourObject()
        .filter(obj=> obj.YourFilterProperty.exactMatch(filterInput))
        .allAsync()
        
    const result = ObjectsToGetAvgTimestampDiff
        .map(rs => rs.timestampClose?.getTime() - rs.timestampOpen?.getTime())
        .reduce((acc, diff) => acc + diff, 0)

return result / ObjectsToGetAvgTimestampDiff.length;

You might have to do additional null / undefined handling on the .map(…) line.

Hope this helps!

Best,

1 Like