How to Pick a Random Element from an Array in Javascript
In this tutorial, you will learn how to pick a random element from an array in javascript. Arrays are just a collection of items. Since the arrays are index-based, we can easily add, replace, or remove an item.
Since javascript is not a strongly typed language, an array can have strings, numbers, objects, or even Boolean values at the same time. We do not have any built-in method for arrays to pick a random item.
In one of the previous tutorials, I have explained how to generate random numbers in javascript within range by using Math.floor()
and Math.random()
methods. We are going to use the same technique with arrays but with slight modification.
We will generate a random number by using the above technique and will use that random number as an index. We will provide that index to the array and retrieve the item at that index position.
In the following example, we have one h1
element and one button
element. Upon click of a button, we will generate a random index number, get the item from the array at that index position and display it on the screen with the help of the h1
element. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,h1
, andbutton
). Thediv
element is just a wrapper for the rest of the elements. - The
innerText
for thebutton
element is“Random”
and for theh1
element, it is“Result”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Random</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
button
element andh1
element using thedocument.querySelector()
method and stored them inbtnRandom
andresult
variables respectively. - We have one global variable
users
and it holds an array of strings. - We have the
getRandomNumber()
method to generate a random number within a certain range. Please check out the previous tutorial to learn more about this random number generation process. The link is given above. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are calling the
getRandomNumber()
method and passing 0 and index of the last item in the array as parameters. We are subtracting 1 fromlength
property of the array because thelength
property will return 8 and we do not have any item at this index. - Due to the above step, the
getRandomNumber()
method will return a number between 0 and 7 and we are storing that in theindex
variable. - We will utilize the
index
to get a random item from theusers
array and display that in theh1
element using theinnerText
property.
let btnRandom = document.querySelector('button'); let result = document.querySelector('h1'); let users = ['Marks', 'John', 'Jane', 'James', 'Mary', 'Peter', 'Simon', 'Ronald']; function getRandomNumber(min, max) { let step1 = max - min + 1; let step2 = Math.random() * step1; let result = Math.floor(step2) + min; return result; } btnRandom.addEventListener('click', () => { let index = getRandomNumber(0, users.length-1); result.innerText = users[index]; });