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]
}

repl

Tagged: Snippets

Leave a comment

Your email address will not be published. Required fields are marked *