Get a random item from a JavaScript array.
Get a random int
First we need to get a random number that is an int and isn’t too large. We
can extract this into a small helper:
const getRandomInt = max => Math.floor(Math.random() * max)Explanation:
Math.floor()- Returns the largest integer less than or equal to a given number.
Math.random()Returns a pseudo-random number between 0 and 1, usually not an integer, but it can be 0, but never 1.
in the range 0 to less than 1 (inclusive of 0, but not 1)
.
Or in a fancier way, with min and max arguments:
const getRandomInt = (max, min = 0) => {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}Get the random array item
Then use bracket notation to access the array at the random index provided by the helper function:
const arr = ['foo', 'bar', 'baz', 'quix', 'fooz']
const randomItem = arr[getRandomInt(arr.length)]How random is that random int generator?
I wrote a post about it, where I’m visualizing that random data.
To be precise, it’s about this random:
