Skip to content

selectRandomElement

Jason Godesky edited this page Jul 11, 2026 · 4 revisions

selectRandomElement returns a randomly-selected element from an array.

Parameters

arr: T[]

An array from which one element is to be randomly selected.

Returns

A randomly-selected element from arr.

Examples

import { selectRandomElement } from '@revolutionarygamesco/common'

selectRandomElement<number>([1, 2, 3]) // Will return 1, 2, or 3

interface TestCase {
  n: number
  label: string
}

const singleCase: TestCase[] = [
  { n: 1, label: 'one' }
]

const cases: TestCase[] = [
  ...singleCase,
  { n: 2, label: 'two' },
  { n: 3, label: 'three' }
]

selectRandomElement<TestCase>(singleCase) // { n: 1, label: 'one' }
selectRandomElement<TestCase>(cases) // Will return one of the objects in cases

See also

Clone this wiki locally