Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda