How to pick a random entry out of an array – JavaScript

Today we bring a bit of fun to the table.

A more appropriate title would have been How to randomly pick an item from an array in JavaScript.

  • How to create a method that picks a random item from an array?

Here’s the whole script just for reference purposes. You and I will be taking it apart as we read down the page:

// selecting a random array item
var selectFruit = ["Apple", "Orange", "Banana", "Cherry"];
var pickAFruit = function () {
var todaysFruit = selectFruit[Math.floor(Math.random() * 4)];
return todaysFruit;
};

To call the function use: pickAFruit();

Ok, roll up your sleeves and let’s dig in. First we test it, then we discuss it line by line.

Fire up your Google Chrome JavaScript console by clicking on the key sequence CTRL+SHIFT+j on Windows or CMD+OPT+j on Mac. NOTE: If this is your first time using the console, click on the bottom left square button to detach the console from the browser and minimize the browser. Make sure you are not reading this blog using the same browser.

Paste the above code to the console. Then use pickAFruit(); to call the function.

You will get a random fruit of the day output. Then, click on the up arrow to repeat the function call, and click on ENTER to repeat the random pick. Do this a few times until you have a good idea of what the script does.

  • How does it work?

First we create the array as shown below. Nothing new there, right?

var selectFruit = ["Apple", "Orange", "Banana", "Cherry"];

Next, we create the function.

In our case, a function is not really necessary. The reason I have chosen a function, is to be able to repeat the function call, without having to retype the script.

var pickAFruit = function () {
};

The magic in this script is on the declaration of the variable todaysFruit:

var todaysFruit = selectFruit[Math.floor(Math.random() * 4)];

The script above, assigns to the variable one of the array items at random.

  • How do we pick the random item from the array?

Math.floor and Math.random will do that for us, because this duo combo will calculate a item location number, ranging from zero to 3.

  • Wait a minute, if it ranges from 0 to 3, how come we coded 4?

That’s the thing that needs to be explained!

What is Math.random in JavaScript? random is a method from the JavaScript Math library, that gives us a random number from zero to 0.999.

What is Math.floor in JavaScript?  floor is a method from the JavaScript Math library, that  removes the decimal portion of a number, rounding it down to the unit.

By including Math.random inside of Math.floor like this, Math.floor(Math.random()), we create one only possible outcome, which is zero. It doesn’t matter what number Math.random comes up with: it will always be rounded to zero.

todaysFruit = selectFruit[Math.floor(Math.random())];

However, zero by itself wouldn’t work for us, because we have 4 items on the array, right?

What we need to do,  is to pick one of the following random numbers: 0, or 1, or 2, or 3.

To accomplish a range of 4 items instead of a range of zero, we multiply Math.random by 4. In this way, the random numbers will range from 0 to 3.999, and Math.floor will drop it to its nearest whole number, so that we get 0 or 1 or 2 or 3. Don’t forget that arrays in JavaScript start counting from zero.

Armed with such knowledge, we then assign those two Math methods to the variable  todaysFruit:

todaysFruit = selectFruit[Math.floor(Math.random( ) *4 )];

This picks a random location from the array of fruits.

  • What if the size of the array is unknown?

As you know, arrays in JavaScript can vary in size. They can shrink or enlarge. To make this script portable, instead of multiplying by 4, we could multiply by the array.length and JavaScript will translate that expression into the correct number. In this way, it wouldn’t matter if the array is  4 items long or 10,000 items long.

The script below, demonstrates how to make it more portable, by substituting the number 4 by the array length property, making the script universal:

var todaysFruit = selectFruit[Math.floor(Math.random() * selectFruit.length)];

NOTE: I cover many of these methods on my latest book

If you love JavaScript like I do, you will enjoy reading it.
Use the free amazon “Kindle for PC” app to read it on your computer.

To wrap up, here’s the whole script again:

// selecting a random array item
var selectFruit = ["Apple", "Orange", "Banana", "Cherry"];
var pickAFruit = function () {
var todaysFruit = selectFruit[Math.floor(Math.random() * 4)];
return todaysFruit;
};

— END OF FILE —

Advertisements

Author: tarau

technical writer, web technologies

1 thought on “How to pick a random entry out of an array – JavaScript”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s