• Selects a random element from an array.

    This function uses randomInt to generate a random index within the bounds of the array and returns the element at that index.

    Type Parameters

    • T

      The type of elements in the array.

    Parameters

    • array: T[]

      The array to pick a random element from. Must not be empty.

    Returns T

    A randomly selected element from the array.

    Will throw an error if the array is empty.

    // Pick a random number from an array
    const numbers = [1, 2, 3, 4, 5];
    const randomNumber = randomPick(numbers);
    console.log(randomNumber); // e.g., 3

    // Pick a random string from an array
    const colors = ["red", "green", "blue"];
    const randomColor = randomPick(colors);
    console.log(randomColor); // e.g., "green"