Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
How to create an unique and random number from an array in Javascript

i'm a super beginner in JS. I try to create a way to generate random unique number (between 0 and 10) by clicking on a button. I want that this number is delete from the array after appearing.

Thank you ๐Ÿ™๐Ÿป

const btn = document.getElementById("btn");

const showNumber = document.querySelector("h2");


let allNumbers = [];
for (var i =1; i <= 10; i++){  
    allNumbers.push(i);
}


const randomNumber = btn.addEventListener('click',()=> {
  let n = Math.floor(Math.random()*allNumbers.length+1);
  showNumber.innerText = n;

 });



 if(allNumbers.indexOf(n+1) === n) {  
    allNumbers.splice(n-1,1);
};
about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

I'm assuming that you want the button to be able to work multiple times, and that you must therefore be able to remove a number from the array no matter where it might be located, as their positions will shift as numbers are removed. You therefore have several problems:

  • The code that selects a random number to remove may choose a number that has already been removed.
  • The code assumes that the number is at a particular position, which may not be true after the first removal.
  • The code that removes the element from the array is currently located outside of the event listener that is invoked when you click the button; you must move it inside the function for it to work.

To avoid the first problem, instead of choosing a random number from 1 to 10 to remove, select a random location in the array:

const index = Math.floor(Math.random() * allNumbers.length);
const n = allNumbers[index];

Then you can just remove that element by index:

allNumbers.splice(index, 1);

Also note that randomNumber is not useful because addEventListener() only ever returns undefined.

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!