Search code examples
jsonata

JSONata group, sort and return first item per group


I have an advanced JSONata request. This is my JSON

[
  {
    "id": "a1",
    "grouping": "A",
    "text": "Lorum ipsum",
    "created": "2023-01-01T13:42"
  },
  {
    "id": "a2",
    "grouping": "A",
    "text": "Epsom minor",
    "created": "2023-02-01T20:02"
  },
{
    "id": "a3",
    "grouping": "B",
    "text": "Ipsum Lorum",
    "created": "2023-01-01T13:42"
  }
]

I would like to group by "grouping", sort by "created" in descending order, and only the first entry per group.

I would like the return result to be

[
  {
    "id": "a2",
    "grouping": "A",
    "text": "Epsom minor",
    "created": "2023-02-01T20:02"
  },
{
    "id": "a3",
    "grouping": "B",
    "text": "Ipsum Lorum",
    "created": "2023-01-01T13:42"
  }
]

Solution

  • This expression should do it:

    $^(>created){ grouping: $ }
      ~> $each(function ($value) { $value[0] })
    

    So, first, we sort the list by created using the order-by operator then, we group it by grouping with the help of the reduce operator, and finally, we pick the first entry within each group using the $each function.

    Check out your example live on the playground: https://stedi.link/Ad4ZDix