Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Created September 29, 2023 23:04
Show Gist options
  • Save christophemarois/512493fd182ce89627b4a48acb4e4ecd to your computer and use it in GitHub Desktop.
Save christophemarois/512493fd182ce89627b4a48acb4e4ecd to your computer and use it in GitHub Desktop.
Zod Unique Array
/** Array where are elements are expected to be unique by a custom key */
export function zUniqueArray<
ArrSchema extends z.ZodArray<z.ZodTypeAny, 'many'>,
UniqueVal,
>(
uniqueBy: (item: z.infer<ArrSchema>[number]) => UniqueVal,
schema: ArrSchema,
) {
return schema.superRefine((items, ctx) => {
const seen = new Set<UniqueVal>()
for (const [i, item] of items.entries()) {
const val = uniqueBy(item)
if (seen.has(val)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Unique property validation failed`,
path: [i],
})
} else {
seen.add(val)
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment