clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Access random element in an array, in a short and concise manner

Filed under: JavaScript— Tagged with: iteration

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. This can be extracted 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 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
}

Get the random array item

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)]

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:

Graph showing a random distribution of numbers

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • console.log('Smash the patriarchy!')
  • I love u!