How to Generate Random Numbers in Javascript without Repetitions

In this tutorial, you will learn how to generate random numbers in javascript without repetitions. The sequence of pseudorandom numbers gets repeated after a certain point in time.  To avoid that, we do need to implement some sort of custom logic.

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 here but with slight modification.

Since we do not want the repetition of random numbers, we will store all the numbers in a certain range within an array. Then, we will start picking a random number from that array one by one and at the same time, we will remove that from the array.

Because we have removed that number from the array, we will never get it again.  Sooner or later, the array will become empty and the random number generation process will stop automatically.

In the following example, we have one h1 element and one button element.  Upon click of a button, we will generate random numbers within a certain range without any repetition 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 2 elements in the HTML file (h1 and button).
  • The innerText for the button element is “Generate” and for the h1 element, it is “Random Number”.
  • We are using the style attribute to horizontally center align the text content inside the h1 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">
    <title>Document</title>
</head>

<body>

    <button>Generate</button>

    <h1 id="output" style="text-align: center">Random Number</h1>

    <script src="script.js"></script>
</body>

</html>

Javascript

  • We have selected the button element and h1 element using the document.querySelector() method and stored them in btn and output variables respectively.
  • We have 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 the createArrayOfNumbers() method and this method takes 2 parameters, start and end. The start indicates the start of the range and the end indicates the end of the range. This method will return an array of numbers.
  • We are calling the createArrayOfNumbers() method and passing 1 and 10 as parameters. As a result, it will return an array with 10 items in it and we are storing that in numbersArray variable.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are using if statement to verify whether the numbersArray is empty or not. If yes, then we will display “No More Random Numbers” in the h1 element and stop the execution.
  • 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 because the length property will return 10 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 9 and we are storing that in the randomIndex variable.
  • We will utilize randomIndex to get a random item from the numbersArray and store that in randomNumber variable.
  • We will remove the item at randomIndex from the array using the splice() method.
  • We will display randomNumber in the h1 element using the innerText property.
let btn = document.querySelector('button');
let output = document.querySelector('#output');

function getRandomNumber(min, max) {
    let step1 = max - min + 1;
    let step2 = Math.random() * step1;
    let result = Math.floor(step2) + min;
    return result;
}

function createArrayOfNumbers(start, end){
    let myArray = [];
    for(let i = start; i <= end; i++) { 
        myArray.push(i);
    }
    return myArray;
}


let numbersArray = createArrayOfNumbers(1,10);

btn.addEventListener('click', () => {
    if(numbersArray.length == 0){
        output.innerText = 'No More Random Numbers';
        return;
    }

    let randomIndex = getRandomNumber(0, numbersArray.length-1);
    let randomNumber = numbersArray[randomIndex];
    numbersArray.splice(randomIndex, 1)
    output.innerText = randomNumber;
});