Get a Random Array Item with JavaScript

By  on  

JavaScript Arrays are probably my favorite primitive in JavaScript. You can do all sorts of awesome things with arrays: get unique values, clone them, empty them, etc. What about getting a random value from an array?

To get a random item from an array, you can employ Math.random:

const arr = [
    "one",
    "two",
    "three",
    "four",
    "tell",
    "me",
    "that",
    "you",
    "love",
    "me",
    "more"
];
const random1 = arr[(Math.floor(Math.random() * (arr.length)))]
const random2 = arr[(Math.floor(Math.random() * (arr.length)))]
const random3 = arr[(Math.floor(Math.random() * (arr.length)))]
const random4 = arr[(Math.floor(Math.random() * (arr.length)))]

console.log(random1, random2, random3, random4)
// tell one more two

As for when you would need random values from an array is up to your individual application. It's nice to know, however, that you can easily get a random value. Should Array.prototype.random exist?

Recent Features

  • By
    From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!

    My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Discussion

  1. It is worth noting if you’ve already got underscore or lodash included in your project, you can simply use _.sample. E.g.

    // will return one item randomly from the array
    _.sample(arr);
    

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!