Generating Unique Random Numbers with JavaScript

Is there a way to generate 5 unique random lottery numbers using JavaScript? I've been working on the code below, but can't seem to figure out how to ensure there are no duplicate numbers in the final selection. I tried adding conditionals and loops like forEach, but it didn't solve the issue. Could you help me with this problem? Here's the current code I'm working with. Thank you.

let lotto = [];
    for(let i = 0; i < 5; i++){
      lotto[i] = Math.floor(Math.random() * 69) + 1;
    }

const sorting = lotto.sort((a,b) => a - b);
    console.log(sorting);

Answer №1

Here are two possible solutions:

  1. Make a list of your numbers and then select 5 by removing them one by one.
  2. Create a loop that continues to generate numbers until it has 5 unique ones.

Your attempt can be modified for the second solution:

let lotteryNumbers = [];
while(lotteryNumbers.length < 5) {
    console.log('Got', lotteryNumbers.length, 'numbers!');
    // Changed 69 to 5 to increase chances of duplicates
    const number = Math.floor(Math.random() * 5) + 1;
    if (!lotteryNumbers.includes(number)) lotteryNumbers.push(number);
}

const sortedNumbers = lotteryNumbers.sort((a, b) => a - b);
console.log(sortedNumbers);

Answer №2

To ensure the process runs at least once, it is recommended to utilize a do-while loop and check if the number already exists in the list.

const lotteryNumbers = [];

do {
    const randomNum = Math.floor(Math.random() * 69) + 1;
    if(!lotteryNumbers.includes(randomNum)) lotteryNumbers.push(randomNum);
} while(lotteryNumbers.length < 5);

const sortedNumbers = lotteryNumbers.sort((a, b) => a - b);
console.log(sortedNumbers);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

From jQuery to ReactJS: Migrating to a Modern

As I venture into converting existing jQuery code to React.js, I must admit that I am quite new to React and still in the learning phase. So please bear with me if my questions sound a bit silly. Here is the structure I am working with: <ul> &l ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

GraphQL is not capable of fetching data directly from a mysql database

Trying to incorporate GraphQL with MySQL in a Node.js Express server has been my recent challenge. Unfortunately, every time I execute my query, an error surfaces. Here is the specific error message: { "errors": [ { "message&quo ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

The AngularJS application appears to have trouble accessing a local text file, even when it is deployed on

Within the same directory of my application deployed on IIS, there are 4 files: home.html Angular.js data.txt web.config (Automatically generated by IIS for default document) I am looking to display the content of 'data.txt' on 'home.html ...

Conceal the scrollbar and enable horizontal swiping using CSS

I have set up a container where I want the content to scroll horizontally from left to right on mobile devices, and I would like to be able to swipe to navigate while hiding the scrollbar. You can view the implementation on this JSfiddle link Do you think ...

What is the best way to calculate the duration of a .wav file stored locally using JavaScript?

Can you help me figure out how to determine the duration (in milliseconds) of a .wav file using JavaScript for a GreaseMonkey Script? The main challenges I'm encountering are: 1) Accessing local files 2) Retrieving the length of the wav file ...

After a two-second period of inactivity, the buttons on the item should trigger an action

I have a scenario in mind that I want to implement: When the user clicks on either the "Plus" or "Minus" button. If the user doesn't click on any of those buttons within 2 seconds, then we assume that the current quantity should be sent to the server ...

How to troubleshoot Path Intellisense in VScode when using jsconfig.json for Next.js

In the structure of my project, it looks like this: jsconfig.json next.config.json components |_atoms |_Button.jsx |_Button.module.scss |_... |_... ... Within the jsconfig.json file, I have specified the following settings: { ...

Recreating elements in ng-repeat using ng-click conditionally

I am attempting to swap an anchor tag with an image when clicked by the user. The code snippet I'm using looks like this: <div ng-repeat="postpart in currentPost.parts "> <div ng-if = "!postpart.isclicked"> <img ng-src= ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

Using jQuery to update the input value when the mouse hovers over a div

Attempting to update an input value using jQuery mouseover. Situation: There are 5 divs with different colors and usernames. When hovering over a div, the input text (and background color for the color input) changes based on database values. Each time a ...

Is utilizing React function components the most effective solution for this problem?

export default function loginUserUsing(loginType: string) { const [state, setState] = useState(loginType); function login() { // body of the login function } function oauth() { // body of the oauth function login(); ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Achieving consistent text alignment in HTML and CSS without relying on tables

As I delve into the world of HTML and CSS, I've taken a traditional approach by crafting a login page complete with three input controls (two text inputs and one button). To ensure proper alignment of these elements, I initially turned to the trusty & ...