How to sort nested categories alphabetically in GROQ query?
Good news - you can definitely sort those nested categories right in your GROQ query! You don't need to handle it client-side.
The trick is to use the order() function directly within your projection. Here's how to modify your query:
*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
...,
"categories": categories[]-> | order(title asc) {
"slug": slug.current,
title
}
}The key changes:
- Wrap the categories projection in quotes to make it an explicit field name (
"categories":) - Add
| order(title asc)right after the reference resolution (->) but before the projection object - The
order()function will sort your categories alphabetically by title
You could also sort by slug if you prefer:
*[_type == "post"] | order(publishedAt desc, _updatedAt desc) {
...,
"categories": categories[]-> | order(slug.current asc) {
"slug": slug.current,
title
}
}The pattern here is that when you want to order elements within a sub-array, you place the order() function in the pipeline after the dereference operator (->) and before the projection's opening brace.
This is much cleaner than handling it client-side and keeps all your data transformation logic in one place!
Show original thread2 replies
Sanity β Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.