Search code examples
javascriptrandomnumbersunique

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);
};

Solution

  • 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.