Function sample

  • Returns a random element from the given array.

    Type Parameters

    • T

      The type of the elements in the array.

    Parameters

    • array: readonly T[]

      The array to sample from.

    Returns T | undefined

    A random element from the given array, or undefined if the array is empty.

    import { sample } from "@std/collections/sample";
    import { assertArrayIncludes } from "@std/assert";

    const numbers = [1, 2, 3, 4];
    const random = sample(numbers);

    assertArrayIncludes(numbers, [random]);