Checking a condition with a for loop in Javascript

I'm working on developing a function that can generate a random number between 0 and 9 that is not already included in an array.

Here is the code I have come up with so far:

 var myArr = [0,2,3,4];

  console.log("Array: " + myArr);

  function newNumber(){
     console.log("testing");

     for (var i = 0; i < 10; i++) {
       var n = myArr.includes(i)
       // I am aiming to only return 'n' if it is not already present in the array
     }
     return n;
  }

newNumber()

I am looking to return a single unique number. Can someone guide me on how I can achieve this?

Appreciate the assistance.

Answer №1

Do you know the answer?

const invalidValues = [5,7,8,9];

const getRandomInt = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const getValidRandomInt = (min, max) => {
  while(true) {
    let temp = getRandomInt(min,max)
      if(!invalidValues.includes(temp)) {
        return temp;
      }
  }
}

console.log(getValidRandomInt(0,15))

Answer №2

let myArray = [1,3,5,7];
  function findNewNumber(){
     for (let j = 0; j < 15; j++) {
       if (!myArray.includes(j)) {
            return j;
       }
     }
     // return -1 if all numbers are already in the array..
     return -1;
  }

findNewNumber();

Answer №3

Utilize the power of Math.random() to generate a number within a specified range. Then, iterate through and verify if the generated number exists in the given array. If the number is not found in the array, return that number:

function generateUniqueRandom(min, max, array) {
  array = new Set(array);
  while(true){
      let value =  Math.floor(Math.random() * (max - min) + min);
      if(!array.has(value)){ return value;}
    }
}
console.log(generateUniqueRandom(0, 15, [7,8,9]));

Answer №4

Solution:

To obtain a random number within a specified range, utilize the formula

Math.random() * (max - min) + min
.

For integer values, either wrap the formula with Math.floor or use a bitwise OR (|) operation for smaller numbers.

function generateRandomNumber(numArray) {
 let randomNum = () => Math.random()*9 | 0,
     num = randomNum();
 while(numArray.includes(num)) {
   num = randomNum();
 }
 return num;
}

Illustration:

var myNumArray = [0,2,3,4];

function generateRandomNumber(numArray){
   let randomNum = () => Math.random()*9 | 0,
     num = randomNum();
   while(numArray.includes(num)) {
     num = randomNum();
   }
   return num;
}

let output = generateRandomNumber(myNumArray);
console.log(output);

Answer №5

let arrayNumbers= [1,3,7];
function getRandomNumber(arrayNumbers, n){
    n ? n : 1;
    let number = Math.random() * n;
    if(arrayNumbers.indexOf( number ) !==-1 ) {
        return getRandomNumber( arrayNumbers, n );
    }
    return number;
}
getRandomNumber(arrayNumbers, 20);

Answer №6

To find the first missing number in the given array, the code snippet provided above suggests looping through a range of numbers and checking if each value exists in the array. Once a value is found to be missing, it is returned as the result.

 var myArr = [0,2,3,4]; // original array

  function findMissingNumber(){

     for (var i = 0; i < 10; i++) { // loop through i from 0-9

       if (myArr.indexOf(i) === -1){ // check for the first missing number
        return i; //return it
       }
     }
  }

findMissingNumber()

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

What is the best way to hear an event emitted by a component?

I am trying to listen for an event in Chrome DevTools Vue, but I'm not sure how to target it. For a Root event, I typically use: this.$root.$on("note_id", (note_id) => (this.note_id = note_id)); But how do I address an event that origina ...

What is the best way to bring up the keyboard on an iPhone when focusing an HTML text field?

Currently working on developing a web app for iPhone, and looking to implement a feature where a text field is automatically focused upon page load, prompting the keyboard to appear. Despite attempting the standard Javascript method: input.focus(); I see ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

Making an "associated" route the active route within Aurelia

In my Aurelia application, I have implemented two routes: a list route called Work and a detail route called WorkDetail. Currently, only the list route is visible in the navigation menu: Home | *Work* | Contact | . . . When users navigate to the W ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

The interaction between a parent element and an iframe, combining mouseover/out events with clicking actions

I am brand new to programming and seeking some guidance. I came across a post about mouseover/out combined with click behavior that I found intriguing. However, I am struggling to implement it successfully in my code. Here is the code snippet: Child.htm ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Obtaining the calculated background style on Firefox

Back when my userscript was only functional on Chrome, I had a setup where I could copy the entire background (which could be anything from an image to a color) from one element to another. This is how it looked: $(target).css('background', $(so ...

Updating several inputs programmatically in VueJSLet's explore how to

I am working on a form that requires updating multiple other fields when one field is updated. For instance, I have a contact name field and depending on the name entered, I need to update the email and phone number fields as well. <template> < ...

How can I effectively monitor and track modifications to a document's properties in MongoDB?

I'm wondering how to effectively track the values of a document in MongoDB. This involves a MongoDB Database with a Node and Express backend. For example, let's say there is a document within the Patients collection: { "_id": "4k2lK49938d ...

Experiencing pagination problems with Vue / Laravel framework

Trying to implement pagination for fetched data in a Vue project, but encountering an issue: New Question Error encountered during rendering: "TypeError: this.estates.filter is not a function" Am I overlooking something here? Pagination.vue ...

What advantages does $sce or Strict Contextual Escaping provide in AngularJS, and why is it unnecessary for React?

I find it perplexing that I am unable to fully grasp the true value of utilizing SCE in AngularJS (even after reviewing the documentation) when it comes to security benefits. It leaves me wondering why React does not require SCE. So, to summarize my quest ...

Difficulty loading AJAX with autocomplete feature. Any suggestions?

I have created a jQuery autocomplete feature that works correctly, but when the value is removed using the Backspace key, the 'LOADING...' message remains visible instead of hiding. How can I make it so that after removing the value with the Back ...

What is the best way to restructure this deeply nested JSON information?

I'm working with the payload structure of my API and I want to format the data in a way that allows for dynamic display on the frontend without hardcoding column names. Currently, I am using DRF, axios, and react-redux, but I feel like I may need to d ...

Guide on transforming UTC time from the server to the local time of users during a GET request

I am currently facing a challenge where I need to verify if the date of the last time an element was clicked matches the current date. Due to my server generating the current date which is 5 hours ahead of my local time, there is a discrepancy causing the ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use ...

Trouble with Click event not working in Electron and mouse cursor not changing when hovering over an HTML button?

I'm in the midst of a project that involves using the electron framework. Within my project, I have an HTML file, a CSS file, and a Javascript file. The issue at hand is that when I hover over a button, the expected hand pointer icon fails to appear d ...

Use jQuery to switch back and forth between two different sets of classes

I am attempting to switch between two different sets of classes using jQuery. My goal is to change from one custom icon to a font-awesome icon upon clicking an element. While I have been successful in changing a single class, I am facing challenges when tr ...

Create a consistent number based on quantity

Looking to generate a sequence of numbers equal to the count in PHP or JavaScript for my application. For example, if my total count is 7: <?php $total = 7; I would like to generate seven 1's like this: $split_one = [1,1,1,1,1,1,1]; If my count ...