Getting random elements from arrays
JavaScriptAll snippets in this category →
Posted on We can combine Math.random()
with the array accessor to get a random element from an array.
// 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)
// 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)
// 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)
// 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)