Hide already selected references from array dropdown in Sanity
Yes, absolutely! You can filter out already-selected references from the dropdown so editors only see options that haven't been added yet. This is a common need and there's a clean solution using the options.filter property on your reference field.
Here's how to set it up. The key is to place the filter on the reference field inside your array, not on the array itself:
{
title: 'Services',
name: 'services',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'service'}],
options: {
filter: ({document}) => {
// Get all currently selected service IDs
const selectedServices = (document.services || [])
.map(service => service._ref)
.filter(Boolean)
return {
filter: '!(_id in $selectedServices)',
params: {
selectedServices
}
}
}
}
}
]
}This works by:
- Extracting the
_refvalues from all currently selected items in your array - Using a GROQ filter to exclude documents whose
_idmatches any of those references - The
.filter(Boolean)removes any undefined values to prevent errors
Making it reusable
If you're using this pattern across multiple fields, you can create a utility function. Here's a reusable approach from the Sanity community:
// utils/getFilter.js
export const getFilter = (document, field) => {
const existingEntries = (document[field] || [])
.map(entry => entry._ref)
.filter(Boolean)
return {
filter: '!(_id in $existingEntries)',
params: {
existingEntries
}
}
}Then in your schema:
import { getFilter } from '../utils/getFilter'
{
title: 'Services',
name: 'services',
type: 'array',
of: [
{
type: 'reference',
to: [{type: 'service'}],
options: {
filter: ({document}) => getFilter(document, 'services')
}
}
]
}This way, once Orthopedics is selected, it won't appear in the dropdown anymore when you go to add another service. The filter updates dynamically as you add or remove items from the array.
You can read more about dynamic reference filters in the Sanity docs and see additional discussion in this community thread about filtering reference arrays.
Happy Friday! š
Show original thread8 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.