An array containing 10 unique numbers

I am looking for an array that contains 10 unique random numbers.

Here is the function I have been using:

    for (i=0;i<10;i++) {
      numbers[i] = Math.floor((Math.random()*10));
      for (j=0;j<i;j++){
        if (numbers[j]==numbers[i]){duplicate=true;}
      }
      if (duplicate){i=i-1;}
    }

Thank you in advance for your response.

Answer №1

Ensure that all your variables are properly declared:

var x = [], k, l, fail;

It's important to reset the variable "fail" before entering the inner loop:

  fail = false;
  for (l = 0; l < k; l++)
    // ...

On a related note, if you need to store 10 numbers in an array with exactly 10 elements, consider populating the array with numbers from 1 to 10 (or 0 to 9) and then shuffling the array. Following this approach can lead to more predictable performance. If you generate random numbers sequentially, the process could vary greatly in terms of efficiency. As you reach the end of the array, it might require only a few attempts or multiple tries; the randomness of the number sequence adds uncertainty.

Answer №2

To optimize the array filling process, one could start by populating it with numbers ranging from 1 to 10, followed by random shuffling as illustrated below:

let myArray = [1,2,3,4,5,6,7,8,9,10];

//shuffle array
//source: http://stackoverflow.com/a/2450976/1223693
let i = myArray.length, j, temp;
if ( i === 0 ) return false;
while ( --i ) {
   j = Math.floor( Math.random() * ( i + 1 ) );
   temp = myArray[i];
   myArray[i] = myArray[j]; 
   myArray[j] = temp;
}

//completed shuffling
alert(myArray);

The current approach may be sluggish due to its inner loop design and the possibility of producing incorrect numbers multiple times before reaching a valid output.

  • It involves repeated iteration
  • There's a high chance of generating erroneous results initially

Answer №3

Are you looking to generate an array consisting of 10 elements, each holding a random number between 0 and 9, with none of the numbers repeating? Essentially, you want to shuffle the numbers 0-9 within these 10 elements?

If so, the solution is simple - initialize the array and then proceed to shuffle it using the following code:

// Function for shuffling array
function shuffleArray(arr) {
    for(let j, x, i = arr.length; i; j = Math.floor(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
}

// Initialize the array:
let myArray = [];
for (let i = 0; i < 10; i++) {
  myArray.push(i);
} 
// Shuffle the array:
myArray = shuffleArray(myArray);

Answer №4

A more streamlined approach could be:

const numbers = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0].sort(
function(){return Math.random() - 0.5});

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

Suggestions for preventing the highlighting of the space between buttons on a webpage

html: <button id='automoney' onclick='minusTen()'></button> <button id='automoney2' onclick='minusHundred()'></button> <button id='automoney3' onclick='minusFiveHundred()& ...

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

PHP script failing to execute if/else statement during AJAX request

I am currently developing a website that heavily relies on Ajax, and I have chosen to use codeigniter for its construction. On the site, there is a form with the post method, and this form is submitted using an Ajax request that calls a function containi ...

Managing ajax requests for lazy loading while scrolling through the middle of the window can be a challenging task. Here are some tips on

I have implemented Lazy loading in my Project. I found a reference at which explains how to make an ajax call after scrolling and image upload with slow mode without allowing scrolling until the loader is shown. The code snippet I am using is as follows: ...

Loop through the array only if the property exists to avoid encountering the 'cannot iterate over undefined' error

Here's a code snippet that I'd like to simplify: if (this.props.fk_data) { if (this.props.fk_data.length > 0) { for (let fk_dataset of this.props.fk_data) { } } } I'm considering putting this.props.fk_data into st ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Issue encountered while attempting to write KML objects to Google Earth API: NPObject error

Currently, I am working on a script that aims to extract data from Facebook and display it graphically on a Google Map using simple extruded polygons. The social integration and AJAX functionality are both working fine for me. However, whenever I try to ex ...

The transformation of a Raphael element does not occur as expected when it is passed to a function within a loop

My attempt to rotate an object by a variable number of degrees in order to mimic a dial was unsuccessful. Initially, I tried the following steps: window.onload = function() { var paper = new Raphael(document.getElementById('canvas_container ...

Having difficulty configuring particlesJS as the background

If you're looking to create a three-page single scrolling webpage with particlesJS as the background, consider using the following resources: particlesJS Website and particlesJS Github Page. An issue arises when trying to set particlesJS as the back ...

Utilizing the fetch() method to transmit GET data within the body rather than directly embedding it in the URL

I am in the process of converting this jQuery call to vanilla JavaScript using fetch() following the guidance provided by MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options). $.ajax( { ...

Nested asynchronous mapping in Node.js involving multiple HTTP requests

Currently, I am attempting to iterate through an array of URLs and retrieve responses from a specific set of URLs. The goal is for the outer loop to only proceed after all inner requests have been completed, resulting in the desired outcome as shown below: ...

I was confused about the distinction between the https.get() and https.request() functions in the Node.js npm package for https

// # Exciting Nodejs Programs! const https = require('https'); https.get('https://www.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on ...

Ionic 2: Image source not being updated

When working with Ionic 2, I encountered an issue where the src attribute of an <img> element was not updating inside the callback function of a plugin. Here is the template code: <img [src]="avatar_path" id="myimg" /> After using the Came ...

Storing user input in a variable - JavaScript Facebook Messenger bot

I am currently developing a facebook messenger bot using node.js. I am looking for a way to store the user response from a message that the bot sends, so that it can be accessed later by using a variable. // defines that 'text' is any message se ...

Utilizing an array for assigning values in conditional statements

I have been experimenting with toggling a CSS style on a couple of elements using an if statement. Currently, I have it working with several if statements, but I believe it can be simplified by utilizing an array with the values and just one if statement. ...

struggling to locate path in Node.js REST API using Express and ES6 classes

I'm currently setting up a RESTful API using Node.js, and I've opted to utilize ES6 classes for the task. This is how my app.js file appears: const express = require("express"); const morgan = require("morgan"); const bodyParser = require("body- ...

The function "onClick" within an external .js file is being referenced

Just starting to learn Javascript and experimenting with an onClick event for an image in an external .js file using the HTML tag. <script type="text/javascript" src="embed.js"> The code found in "embed.js" is as follows: var image1=new Image(); i ...

Enhance Vaadin 14: Automatically adjust TextArea size when window is resized

Using Vaadin 14.1.19 in a project called "My Starter Project," I attempted to create a TextArea that supports multiple lines. Initially, everything seemed fine, but upon resizing the TextArea, it failed to adjust the number of visible lines. Here is the co ...