Getting random elements from arrays

Getting a random number is fun, but it’s not “getting a random element from an array” fun. I don’t know why you’d want to do this, but you can.

// get a random element from the given array
const sample = array => array[Math.floor(Math.random() * array.length)]

// every time we use `sample`, it returns a random element
sample([17, 6, 22, 13, 9])  // ⇒ 13 (maybe)
sample([17, 6, 22, 13, 9])  // ⇒ 6  (maybe)
sample([17, 6, 22, 13, 9])  // ⇒ 6  (maybe)
sample([17, 6, 22, 13, 9])  // ⇒ 17 (maybe)

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.