How to Get a Random Item from an Array in Javascript

Share
In this article, we'll learn how to get a random item of an array in Javascript (Typescript), such that, for example, if you have an array of items ['red', 'green', 'blue'], you will be able to randomly select a color. Although this tutorial is for Javascript, the exact same algorithm should work in most programming languages.

To do this, the Typescript code is very simple:

function pickItem<T>(items: T[]): T | undefined {
    const idx = Math.floor(Math.random() * items.length);
    return items[idx];
}

Let's understand what the code above does.

First, <T>, : T[], and : T | undefined are Typescript code. If you use plain Javascript instead, you can remove these.

The <T> is necessary so we can say that this function takes an array of some type T, and returns a value of the same type as the elements of the array.

The important API here is Math.random(). It generates a pseudorandom number from zero to one. This means the number returned can be 0.3, but will never be 1.3. More specifically, value returned can be zero, but it is always less than one. Every programming language has a similar API. Pseudorandom simply means that the number is generated based on a deterministic algorithm so it isn't truly random. For most programs except high-security cryptography, pseudorandom is random enough.

We will take this range [0..1) and extend it to [0..items.length). We do this by multiplying the value we got with the length of the array. Let's say our array has 3 items. Its length will be 3. Javascript arrays are zero-indexed, so to access the last item we use items[2], not items[3], so how does multiplying the value we got by 3 is supposed to work?

If the random value returned is 0.9999, then 0.9999 * 3 = 2.9997. That's not 2, but it's not 3 either. In fact, it's extremely unlikely that we'll get a whole number from this multiplication. Our arrays only work with whole integers, so we need to convert this fractional number (or a float, floating-point number in some languages) to an integer by rounding it down. We do this by using the function Math.floor in Javascript.

It's worth noting that the typical programming language will have a function for rounding down (floor), rounding up (ceil), and rounding to the nearest integer (round). We want to round down.

If we round up, then 2.997 becomes 3, and since our zero-indexed array only has 3 items, the only valid indexes are 0, 1, and 2. Not 3. 3 will be too much.

Then we can simply return the element in the array from the index we got.

Zero Length Case

In Javascript, if the array has zero elements, then idx will always be 0, and items[0] will return undefined. That's not the case in all languages, however. For example, in Python, trying to access the zeroth element of a list of zero length results in an IndexError. In such cases, you need to check the length first.

import random
import math

def pickItem(items, default=None):
    if len(items) == 0:
        return default

    idx = math.floor(random.random() * len(items))
    return items[idx]
Written by Noel Santos.

About the Author

I'm a self-taught Brazilian programmer graduated in IT from a FATEC. In a world of increasingly complex and essential computers, I decided to use my technical expertise in hardware, desktop applications, and web technologies to create an informative resource to make PC's easier to understand.

View Comments