How to get multiple, random, unique elements from a JavaScript array

As a note to self, this JavaScript code gets multiple, random, unique elements from a JavaScript array and displays three of those elements in the second div:

<html>

<body>

<div id="one">
  <p>one</p>
</div>

<div id="two">
  <p>two</p>
</div>

<script>
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

var arr = [
    "<span class=\"booklink\"><a href=\"/one\">one</a></span>",
    "<span class=\"booklink\"><a href=\"/one\">two</a></span>",
    "<span class=\"booklink\"><a href=\"/one\">three</a></span>",
    "<span class=\"booklink\"><a href=\"/one\">four</a></span>",
    "<span class=\"booklink\"><a href=\"/one\">five</a></span>"
]

/* note: the javascript that updates the div had to be near the end
 * of the body to work (probably just after the div)
 */
shuffle(arr);
document.getElementById("one").innerHTML = arr.slice(0,3).toString();
</script>

</body>
</html>

I don’t write about JavaScript too often, but this code seems like it’s worth sharing. Also, I found the shuffle/randomize code on Stack Overflow, but at the moment I can’t find the page I found it on.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.