Last Updated: February 25, 2016
·
2.718K
· darthlukan

JS: Random int based on length of array

Here's a template that I keep handy anytime I need to return a random anything from an array.

function randomize (yourArray) {
    randint = Math.floor(Math.random() * yourArray.length);
    return randint;
};

Let's say that you're writing an application that displays random quotes to the user as I do here in this application: http://goo.gl/6zNAF (GitHub repo). If your quotes are all contained in one array, you'll want a simple and reliable way of accessing that array without ending up with "index out of range" errors. The best way then is to use the array.length attribute directly.

In the above function we take our array as an argument. We wrap Math.random() * array.length inside of Math.floor() because where random() rounds up or down to the nearest number, floor will always round back down to a whole number which is what makes sure that we're never out of our index range. The resulting number is an integer and can now be used as an index in our lookup.

There are two simple ways that we can use this:

var randint = randomize(quotes);
var quote = quotes[randint];
console.log(quote);

or:

var quote = quotes[randomize(quotes)];
console.log(quote);

I prefer the second as it's less lines to read without sacrificing readability. The nice thing about this function is that, while it's dead simple, everyone has a "brain fart" at some point, especially when working with multiple languages at a time. I personally flip between JavaScript/jQuery, Python, and C on what seems like a per-minute basis everyday. Having a quick little drop-in function like this is just one less thing to have to try and remember when sifting through documentation and bouncing between libraries in different languages.

Enjoy :)