Query last 10 elements from array in Sanity GROQ
GROQ doesn't support negative indices in array slicing the way you might expect from other languages. Your syntax links[(count(links) - 10))...count(links))] has a couple of issues.
To get the last 10 elements of an array in GROQ, you have a few options:
Option 1: Use negative indices with a slice (Recommended)
GROQ does support negative indices! According to the GROQ pipeline components documentation, negative range endpoints are based at the end of the array. You can use:
*[_type == "archives"] {
title,
slug,
"lastTenLinks": links[-10..-1]
}This syntax [-10..-1] means "from the 10th-to-last element to the last element."
Option 2: Order and slice from the beginning
If you want to be more explicit or if negative indexing doesn't work in your GROQ version, you can reverse the array and take the first 10:
*[_type == "archives"] {
title,
slug,
"lastTenLinks": links | order(@) | [0...10]
}However, this approach may not preserve the original order.
Why your original query failed
Your query links[(count(links) - 10))...count(links))] has these problems:
- Extra parenthesis: You have
(count(links) - 10))with double closing parens - Non-literal range: According to the GROQ documentation, "The range must be a literal range due to parser ambiguity with filters" - you can't use computed values like
count(links)in the slice syntax - Three dots vs two: Use
..(two dots) to include both endpoints, or...(three dots) to exclude the right endpoint
The solution
Use the negative index approach with two dots (which includes both endpoints):
*[_type == "archives"] {
title,
slug,
links[-10..-1]
}This will gracefully handle arrays shorter than 10 elements - it'll just return whatever is available. The negative indices are based at the end of the array, so [-10..-1] gives you the last 10 items (or fewer if the array is shorter).
Show original thread7 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.