Random Number Generator JavaScript without Repetition

Random Number Generator JavaScript without Repetition
Code Snippet:Generating array of random numbers without repetition
Author: P. Caleb Ogunwale
Published: May 12, 2024
Last Updated: May 12, 2024
Downloads: 56
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a random number generator without repetition. It helps create unique sets of numbers. When you click “Generate,” it displays an array of ten unique random numbers.

You can use this code in web projects needing unique random numbers. It ensures each generated number is distinct. This code simplifies the process of creating random, non-repetitive data sets.

How to Create a Random Number Generator in JavaScript without Repetition

1. Start by adding the necessary HTML elements to your project. In our case, we have a <h3> element with an ID of “array” to display the generated numbers and a <button> element with an ID of “generate” to trigger the generation process.

<h3 id="array"></h3>
<button id="generate">Generate </button>

2. While not essential for functionality, you may want to add some CSS to style your elements. In our example, we’ve added some basic styles to ensure the display looks presentable.

h3{
   margin-bottom: 30px;
}

3. Now, let’s dive into the JavaScript code. We begin by adding event listeners to ensure our generate function is called when the page loads and when the “Generate” button is clicked

window.addEventListener("load", () => {
  generate();
});
let buttonClicked = document.getElementById("generate");
buttonClicked.addEventListener("click", () => {
  generate();
});
const generate = () => {
  let arrayContainer = []; // this arrays holds the five random numbers generated;
  let displayContainer = document.getElementById("array");
  const genNum = Math.floor(Math.random() * 10);
  arrayContainer.push(genNum);
  console.time();
  for (let counter = 0; counter < 9; counter++) {
    //the counter is less than five because we already initialise arrayContainer[0] with genNum
    let newGen = Math.floor(Math.random() * 10);
    while (arrayContainer.lastIndexOf(newGen) !== -1) {
      newGen = Math.floor(Math.random() * 10);
    }
    arrayContainer.push(newGen);
  }
  console.timeEnd();
  console.log(arrayContainer);
  displayContainer.innerHTML = "[" + arrayContainer + "]";
};

That’s all! hopefully, you have successfully created a random number generator in your web/app project. If you have any questions or suggestions, feel free to comment below.

Leave a Comment