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, and button). The div element is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Random” and for the h1 element, it is “Result”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script 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 and h1 element using the document.querySelector() method and stored them in btnRandom and result 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 the button 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 from length property of the array because the length 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 the index variable.
  • We will utilize the index to get a random item from the users array and display that in the h1 element using the innerText 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];
});