Skip to content

Feature request: an array that drops invalid elements instead of failing #6720

Open

Description

@bvandrc

z.array(x).catch(...) is all-or-nothing. For stored data written against an older shape, or edited by hand, one bad entry costs the whole array, and whatever contains it.

const Tags = z.array(z.object({ id: z.number() }));
Tags.parse([{ id: 1 }, { legacy: true }, { id: 2 }]); // ❌ the whole array fails

The userland workaround is z.array(x.optional().catch(undefined)).transform(filter). It has two problems:

  • It breaks for elements that accept undefined. undefined is the marker for a dropped entry, so a legitimate undefined element gets dropped along with the bad ones.
  • It breaks inference in recursive schemas. Inside a getter-based recursive schema, the .catch()/.transform() collapses the inferred type to unknown[], so pruning a tree of rules or groups has to go through z.preprocess and a cast instead.

Proposed: an array option that drops elements that fail to parse and keeps the rest in order, while a non-array still fails:

const Tags = z.array(z.object({ id: z.number() }), { dropInvalid: true });
Tags.parse([{ id: 1 }, { legacy: true }, { id: 2 }]); // [{ id: 1 }, { id: 2 }]

Size checks like .max() would apply to what survives. The recursive case keeps its full type and prunes at every level.

To keep zod/mini's arrays at zero cost, this could live entirely in Classic's ZodArray, as its own parse loop installed only when the flag is set, with no change to core.

Activity

  1. bvandrc commented on Nov 3, 2026

    @bvandrc
    Author

    Here is my custom schema helper for this:

    /**
     * An array of `element`, with entries that don't parse dropped rather than
     * failing -- so one unrecognised entry costs itself instead of the array and
     * whatever contains it.
     */
    export const arrayDroppingInvalid = <T extends z.ZodType>(element: T) =>
      z.array(element.optional().catch(undefined))
        .transform((values) =>
          values.filter((value): value is z.output<T> => value !== undefined)
        )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions