Get random element from array
5 April 2022 (Updated 13 November 2022)
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
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment