How to maintain order when joining data from documents in an array of document references in Sanity.io
The issue you're experiencing is a common gotcha with GROQ queries! When you use *[_id in ^.services[]._ref], you're creating a new query that fetches all matching documents, but GROQ doesn't automatically preserve the original array order - it returns them in whatever order the Content Lake provides them.
The good news is there's a much better solution than maintaining a separate order array on the client side. You should dereference the array directly using the -> operator instead of doing a separate query. This preserves the original order:
*[_id == "home-page"][0] {
"_page_id": _id,
_updatedAt,
title,
hero_image,
"services": services[]-> {
_id,
title,
summary,
poster,
},
}The key change is services[]-> instead of your separate *[_id in ^.services[]._ref] query. The reference access operator (->) dereferences each item in the array while maintaining the original order.
Here's what's happening:
services[]iterates through your array of references in order->dereferences each reference to get the full document- The projection
{ _id, title, summary, poster }selects only the fields you need
This approach works because you're not creating a separate query that searches for matching documents - you're directly following the references in the order they appear in your array. The -> operator internally performs the lookup for each reference while preserving array position.
This is the standard pattern for working with arrays of references in GROQ and will give you Service A, Service B, Service C in exactly the order you have them stored in your services array. No more client-side matching needed!
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.