Sanity Pioneers: Get early access to betas, extra AI credits, and a direct line to the engineering team. Apply now

Remove single instance from array of duplicate references in Sanity

4 repliesLast updated: Nov 29, 2025

Hi everyone. I am struggling to remove references from an array of references. The array contains up to three references with the same ID.I am only able to remove everyone with the same ID, or no one at all.
This removes all with the defined ID.

const action = unset(

[{_ref: cardId}]

);

onChange(PatchEvent.from(action));

}
Is it possible to remove only one instance? By querying all instances of an ID in an array, and target the first in that list for example? Something like this:

const action = unset(

[{_ref: cardId}][0]

);

onChange(PatchEvent.from(action));

}

Thanks!
AI Update

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:

const action = unset(`[${index}]`); // removes item at specific index
onChange(PatchEvent.from(action));
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 thread
4 replies

Was this answer helpful?

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.

Related contributions