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):

function randomElement(array) {
  const randomIndex = Math.floor(Math.random() * array.length)
  return array[randomIndex]


Tagged: Algorithms