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
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

  • By
    Color Palette Generator Using jQuery

    As I continue to learn jQuery, I think it's important that I begin by porting over scripts I've created using MooTools. One of those scripts is my Color Palette Generator script, which debuted on Eric Wendelin's blog. For those of you that...

  • By
    MooTools History Plugin

    One of the reasons I love AJAX technology so much is because it allows us to avoid unnecessary page loads.  Why download the header, footer, and other static data multiple times if that specific data never changes?  It's a waste of time, processing, and bandwidth.  Unfortunately...

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!