Accessing a Random Element from an Array Using JavaScript

Hero image for Accessing a Random Element from an Array Using JavaScript. Image by davisuko.
Hero image for 'Accessing a Random Element from an Array Using JavaScript.' Image by davisuko.

This Article is Over Eleven Years Old...

Things can and do move very quickly in tech, which means that tech-related articles go out of date almost as soon as they have been written and published. If you are looking for up-to-date technical advice or opinion, it is unlikely that you will find it on this page.

You may find that my recent articles are more relevant, and you are always welcome to drop me a line if you have a specific technical problem you are trying to solve.

There are a decent number of use cases for accessing random elements from within an array when working with websites. For instance, you may have a 'randomise' button on your web app, in which case you'll inevitably want to select a random element from a dataset.

JavaScript offers an easy way to generate random numbers, and we can use that to access random elements in arrays. Let's get into it:


Math.random()

In JavaScript, Math.random() is a function that returns a 'random' floatingpoint number of 16 decimal places, which is greater than or equal to zero and less than one. We can use this as a seed to generate the index we're going to use to randomly access items from our array.

Obviously, we can't access these array items with floats or sixteenpoint decimals, we need integers to do that. To make use of Math.random() effectively we will create a function that can multiply the result of Math.random() by the length of our array. This will return a random number anywhere between zero and the length of our array.

We will also use Math.floor(), to ensure that the value returned is a whole number and not a float. Here's an example function that you can use for this:

function randomNumber(maxNumber) {  return Math.floor(Math.random() * maxNumber);}// this will return a random number between 0 and 90console.log(randomNumber(90));

If you've been following recent updates on ES6 and want to try out arrow function expressions instead (assuming your browser will support it), the same utility could be written as:

const randomNumber = (maxNumber) => Math.floor(Math.random() * maxNumber);

So, in order to use this to access a random item within an array, we can simply place the function call in lieu of an index when selecting from an array:

const countries = [  'Australia',  'Austria',  'Argentina',  'The Bahamas',  'Bangladesh',  'Barbados',  'Belgium',];console.log(countries[randomNumber(countries.length)]);

This will return a random entry from the countries array to your console.


Categories:

  1. Development
  2. ES6
  3. Front‑End Development
  4. JavaScript