Use median value of array as parameter in query

114 Views Asked by At

I want to use the resulting median as the parameter for calculating "larger". How can I do this?

{
  "h": {
  "data": 
    [1,3,5,2,6,8,4,23,7,3]
  }
}

jsonata expression:
[{
    "median" : $sort(h.data)[5],
    "larger" : h.data.($ > 5)
}]   

https://try.jsonata.org/1x8emp3oK

1

There are 1 best solutions below

0
On

Solution - The key you're missing is the usage of variables. Also, the median of your set is 4.5, not 5 because the count of values is even, so the median becomes an average of two middle numbers.

In my solution, I calculate median, assign it to a variable using $variable_name := <calculation> syntax, and refer to that result further in the array filtering.

Keep in mind that if you're using variables, whole expression must be wrapped in parenthesis ( ... ).