Getting array subset in GROQ using start and end _key values
I understand you're looking to get a subset of an array between two specific _key values in GROQ. Unfortunately, GROQ doesn't have a built-in way to slice arrays based on _key positions like you might find in some programming languages with indexOf() or similar functions.
The challenge is that GROQ's slice component only works with numeric indices (like [0..5] or [2...10]), not with dynamic positions based on element properties like _key. There are no functions like array::position() or array::indexOf() that would let you find the numeric index of an element by its _key.
What GROQ can do:
Filter by a single _key:
*[_type == "post"]{
body[_key == "KEY_HERE"]
}Filter by multiple _key values:
*[_type == "post"]{
body[_key in ["key1", "key2", "key3"]]
}Workarounds for your use case:
Since GROQ doesn't support finding the index of an array element by _key, you'll need to handle this logic outside of GROQ:
1. Fetch the full array and slice client-side (recommended):
*[_type == "post"]{
_id,
body[]
}Then in your JavaScript/TypeScript:
const startIndex = body.findIndex(item => item._key === startKey);
const endIndex = body.findIndex(item => item._key === endKey);
const subset = body.slice(startIndex, endIndex + 1);2. Use explicit _key filtering if you know all the keys:
If you know all the _key values between your start and end points, you can explicitly list them:
*[_type == "post"]{
body[_key in ["startKey", "middleKey1", "middleKey2", "endKey"]]
}3. Consider restructuring your data: If you frequently need to query subsets of arrays this way, you might want to store metadata about array positions or create separate documents for array items that need this kind of querying.
The GROQ language is intentionally designed to be simple and declarative, which means some operations that are common in imperative programming languages need to be handled in your application code instead. This slice-by-key operation is one of those cases where it's better suited for client-side processing after fetching the data from the Content Lake.
Show original thread33 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.