Array/Since
1.38.0sample
Returns a randomly selected element from an array.
sample(array):T | undefinedParameters
arrayT[]requiredThe array from which a random element should be selected.
Returns
T | undefinedA randomly selected element from the array, or undefined if the array is empty.
Examples
01
Basic usage
Select a random element from an array of numbers.
TypeScript
import { sample } from "@cyref/js";
const numbers = [10, 20, 30, 40, 50];
const result = sample(numbers);
console.log(result);
// One of: 10, 20, 30, 40, 5002
With strings
The function can randomly select an element from an array of strings.
TypeScript
import { sample } from "@cyref/js";
const languages = [
"JavaScript",
"TypeScript",
"Python",
];
const result = sample(languages);
console.log(result);
// One of: "JavaScript", "TypeScript", "Python"03
With objects
The function returns a randomly selected object from the array.
TypeScript
import { sample } from "@cyref/js";
const users = [
{ id: 1, name: "Amir" },
{ id: 2, name: "Sara" },
{ id: 3, name: "Reza" },
];
const result = sample(users);
console.log(result);
// One of the objects from the users array04
Empty array
An empty array returns undefined.
TypeScript
import { sample } from "@cyref/js";
const result = sample([]);
console.log(result);
// undefinedBuilt with@cyref/js·Official documentation