By Alvin Alexander. Last updated: April 18, 2018
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.