A good[ish] website
Web development blog, loads of UI and JavaScript topics
Get a random item from a JavaScript array.
First we need to get a random number that is an int
, and isn’t too large. This can be extracted into a small helper:
const getRandomInt = max => Math.floor(Math.random() * max)
Explanation:
Math.floor()
Math.random()
in the range 0 to less than 1 (inclusive of 0, but not 1).
Or in a more fancy 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
}
Then use the angle bracket syntax to access the array at the random location provided by the helper function:
const arr = ['foo', 'bar', 'baz', 'quix', 'fooz']
const randomItem = arr[getRandomInt(arr.length)]
I wrote a post about it, where I’m visualizing that random data.
To be precise, it’s about this random:
Comments would go here, but the commenting system isn’t ready yet, sorry.