Picking a Random Item from an Array

by kirupa   |   7 July 2012

Let's say you have an array called myShows that contains a list of some awesome TV shows that you like to watch:

my favorite tv shows

Here is the problem. With so many great shows, how do you know what you want to watch at any given time? Unfortunately, you are unable to pick a show and stick with it beyond the first few seconds of the opening credits. Your friends all give different answers. Your parents haven't even heard of these shows, so they can't help you out much. Your psychiatrist stopped returning your calls. You are stuck.

Fortunately, whenever I find myself in a situation where I am all alone and having to make a difficult choice, I do what I do best. I put all of my choices into an array and write some JavaScript to randomly pick a choice - a choice that I unquestioningly follow.

In this tutorial, you will learn how to write this JavaScript yourself. You will learn how to write some code to randomly pick an item from array filled with items.

Code for Picking a Random Array Value

The code for picking a random value from an array is quite simple:

var randomValue = myArray[Math.floor(Math.random() * myArray.length)];

Replace myArray with the name of the variable that actually stores your array. That's it. Let's look at an example that fully demonstrates this.

First, let's start with our array:

var myShows = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 
'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter'];

Our array is called myShows, so using the code I provided earlier, the way you pick a random value from this array is by doing this:

var show = myShows[Math.floor(Math.random() * myShows.length)];

If you run this code, your show variable will store the name of a randomly picked show from your myShows array.

How This All Works

The technique behind making our one line of code work requires only a slight understanding of arrays and how to work with random numbers.

Let's look at the random numbers angle first. The basic formula for picking a random number between a range of numbers is:

Math.floor(Math.random() * (1 + High - Low)) + Low;

All you need is a high number and a low number to define the range of numbers you want. This code will randomly (and fairly!) pick a random number between your range. The details of this are outlined in my Random Numbers tutorial.

What is the high number and the low number in our case? Since we are dealing with arrays, we know that the position of an item in an array is based on an index number. This index number starts at 0 and increments by one until you hit the end:

the index positions

The low number for us will be 0. This corresponds to the first item in our array. The formula right now will look as follows:

Math.floor(Math.random() * (1 + High));

The high number is the last item in our array. The index position of the last item in your array can be found by taking the length of your array and subtracting that value by 1:

var lastItem = myArray.length - 1;

If I substitute myArray.length - 1 into the high variable in my formula, here is what I would get:

Math.floor(Math.random() * (1 + myArray.length - 1));

The 1's will cancel out leaving your random index position to be:

Math.floor(Math.random() * myArray.length);

Getting the index position takes us most of the way there. We will use this index position to retrieve the value associated with it in our array:

var value = myArray[Math.floor(Math.random() * myArray.length)];

Replace myArray with myShows to get the exact syntax you saw a few hundred pixels earlier.

Conclusion

So there you have it. By simply combining your knowledge of arrays and random numbers, you can create a single line of code that randomly picks a value from an array. In case you were wondering, here is what the script told me to watch:

go watch dexter

I guess that is what I am going to do for the next few hours. See you all later!

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT DO YOU THINK?

NEWSLETTER

No spam. No fluff. Just awesome content sent straight to your inbox!

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!