Creating a unique array of non-repeating numbers in ES6:

Looking to create an array of unique random numbers in ES6 without any repeats.

Currently, my function is generating an array of random numbers that are repeating:

winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));

Here is a non-ES6 solution that I came across: Non-ES6 solution

The solution using Set is not working within a for-loop:

for (let i = 1; i <= draws; i += 1) {
      // Generating a random array of 6 number

      const winArray = new Set();
      while (winArray.size < 6) winArray.add(Math.floor(Math.random() * 53));
}

Answer №1

If you want to generate a set of random numbers, you can use the Set object and add numbers to it until reaching the desired size.

var numbers = new Set;

while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53));

console.log(...numbers);

To generate multiple sets of random numbers, you can create a new empty set for each draw.

var numbers,
    draws = 5,
    i;

for (i = 0; i < draws; i++) {
    numbers = new Set;
    while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53));

    console.log(...numbers);
}

Answer №2

The uniqueness of properties is ensured when using a Set in JavaScript.

let winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));

winArray = [...new Set(winArray)]

console.log(winArray)

Answer №3

This code offers a solution for randomizing a list of distinct numbers without any duplicates.

for (let unique=[],index=0;index<100;++index) unique[index]=index;

function mixup(array) {
  let tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

unique = mixup(unique);

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

The feature of Google street view is not supported within the tabs on WordPress

I'm experiencing some issues with displaying Google maps and street view using the Wp Google Map WordPress plugin within tabs. The map displays perfectly on the first tab where I placed the short code for the map, but on the second tab where I placed ...

Preventing variables from reinitializing in express.js

Within my app.js file, I invoke a search function that communicates with an LDAP server. Upon doing so, the server sends back a cookie which is essential for my subsequent queries. My intention was to save this cookie as an app.local variable in my app.j ...

I am only able to trigger my AJAX request once

Whenever I click on a checkbox, an ajax function is triggered. This function sends a query string to a PHP script and returns relevant HTML. Strangely enough, if I first select a dropdown option and then check another checkbox along with the previous one ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Express.js allows users to define a parent root folder domain

My Express Node.js application is structured as follows: app.get('/', page.index); //Add new, edit and delete form app.get('/approval', page.approval); //Task to approve/reject the subordinate form app.get('/task', page.task ...

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu. What I want is for the sub-menu to close whenever a click occurs outside of it. I attempted a solu ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Bring back enhanced assortment using Mongoose

I am currently working with a stack that includes nodejs, express, mongoose, and angularjs. My task involves updating a collection called Lists which contains various properties, including an array of items. The issue I am facing is that when I push a new ...

What is the most effective way to transfer data from a child component to a parent component when the child component contains multiple input fields?

Passing data from a parent component to a child component is something I need help with. Let's say I have a parent component with the following data: Parent component <template> <NameUser :data="userData"></Name ...

The React application is being continuously accessed by a node.js server and processed within async functions

Currently, I am utilizing React, MongoDB, Node.js, and Express in my project. The specific scenario I am facing involves the following code snippet within my component: renderWishlist(){ var quantity; var itemID; var tmp; var my ...

A step-by-step guide on integrating PDF.js with Vue 3 and accessing the distribution folder locally

I must clarify that I am restricted from using any vue libraries to preview PDFs; only pure pdf.js and vue 3 are permitted. Utilizing pdf.js for presenting PDF files within my vue 3 project. Inquiring about the ideal folder structure for the project to en ...

Tips for building an interactive jQuery data table using JSON information and AJAX requests

Currently, I am attempting to develop a dynamic data table using jQuery and JSON. My objective is to extract the keys from the JSON data and utilize them as headers in the table, while the values within those keys will be displayed as rows. Here's th ...

The request to http://localhost:5000/error resulted in a 404 (Not Found) error message. I encountered difficulties connecting

When attempting to retrieve information about a product from Amazon using their productId with Express.js and ScraperAPI, an error is encountered: Error message: "{name: "RequestError", message: "Error: Invalid URI "${baseUrl}&url=https://www.amazon.com/d ...

Unlock the secrets of programming with the must-have guide to mastering variables

As a newcomer to the world of programming, I may be jumping ahead by asking this question too quickly. While reading a book, I came across something that confused me. Why is it necessary to create a variable for the password box element? Wouldn't the ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Looking to have a countdown begin automatically as soon as the page loads?

Is there a way to create a time counter in jQuery/JS that begins counting when a visitor first enters my website (on page load)? I am looking for a function or similar solution to track the length of time a visitor spends on my website (in seconds) so tha ...