
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGood 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:
"categories":)| order(title asc) right after the reference resolution (->) but before the projection objectorder() function will sort your categories alphabetically by titleYou 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!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store