sajad torkamani

You want a function that takes an array and returns an element at random. Something like this:

const words = ['apple', 'orange', 'banana', 'pear', 'cucumber', 'kiwi']

randomElement(words) // orange
randomElement(words) // cucumber
randomElement(words) // another random element

Here’s how in JavaScript (though the approach should work in other languages):

export function randomElement<T>(array: T[]): T {
  const randomIndex = Math.floor(Math.random() * array.length)
  return array[randomIndex]


Tagged: Snippets