Remove single instance from array of duplicate references in Sanity
I can see from the discussion you found that the key to removing a single reference from an array (rather than all matching references) is to target by the unique _key property instead of matching on _ref.
When you use unset([{_ref: cardId}]), it removes all array items where the _ref matches that ID. This is because the path selector matches every occurrence in the array.
The solution from the community discussion was to generate unique _key values for each array item and target those specifically:
// Generate keys that include a counter (e.g., "01026-1", "01026-2")
const action = unset(`[{ _key: ${cardId}-${index} }]`);
onChange(PatchEvent.from(action));This works because each array item in Sanity has a unique _key property. By targeting a specific key, you remove only that one instance.
Alternative approaches you can consider:
- Use array index position: If you know the position of the item you want to remove, you can use array index syntax as documented in the HTTP Patches documentation:
const action = unset(`[${index}]`); // removes item at specific index
onChange(PatchEvent.from(action));- Use the Sanity Client for more control: Instead of
PatchEvent, you could use the client's patch operations which give you more flexibility with array manipulation:
client
.patch(documentId)
.unset([`arrayField[_key == "${specificKey}"]`])
.commit();The key takeaway: Always target by _key when you need to remove a specific instance from an array that contains duplicate references. The _key is automatically generated by Sanity for each array item and is guaranteed to be unique within that array, making it perfect for targeting individual items even when their content (like _ref values) is identical.
Show original thread4 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.