👀 See Sanity in action: Watch product demo now →

GROQ - Is it possible to Order Items Conditionally Based on the Value of the Field?

5 replies
Last updated: Jan 20, 2022
Is there a way using GROQ to order items conditionally based on the value of the field? e.g. the schema has a field “sorting” that can be ‘popularity’, ‘alpha’ or ‘price’, and the schema has a field with an array of references - is there a way to sort the references based on whatever the sorting is?
Jan 20, 2022, 10:03 AM
On a second thought, it’s probably best to do that on the client side.
Jan 20, 2022, 10:09 AM
Perhaps something like this?

*[_id == "config"][0] {
  sorting,
  "sorted": select(
  	sorting == "price" => docs[]-> | order(price desc),
    sorting == "popularity" => docs[]-> | order(popularity desc),
    docs[]-> | order(alpha desc)
  )
}
You can play w it on the playground here

https://groq.dev/Sx12FCMKhkVe1MhTKefFIW
Jan 20, 2022, 10:53 AM
I was thinking along those lines, but didn’t want to repeat the docs projection multiple times.
Jan 20, 2022, 10:56 AM
yeah, I don't know a way to pass field name to
order()
dynamically
Jan 20, 2022, 10:58 AM
You can't use a projection for sorting, I'm afraid. There's a bit more on that in this thread.
Jan 20, 2022, 4:14 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in