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

201
Vistas
How to generate Random numbers, then exclude array of numbers

i would like to generate random numbers from 1-50, then exclude an array like; 4,7,10,20,35 etc

i tried this;

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
if (!exclNum.includes(mainNum)) {
  console.log(Math.floor(Math.random() * mainNum) + 1)
}

but it still generates numbers that's still in the array, please is there anything i am missing?

Thanks for your response in advance

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You need to generate the random number first, then check if it's in the array. Do this in a loop until it's not in the array.

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];
let ranNum;
while (true) {
  ranNum = Math.floor(Math.random() * mainNum) + 1;
  if (!exclNum.includes(ranNum)) {
    break;
  }
}
console.log(ranNum);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are currently checking whether exclNum includes mainNum, which is 50.

Instead, generate the random number and check whether exclNum includes it:

let mainNum = 50
let exclNum = [4, 7, 10, 20, 35];

while(!exclNum.includes((randomNum = Math.floor(Math.random() * mainNum) + 1))){
  console.log(randomNum)
  break;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar

0

A do... while loop is more concise

function myRandom(mainNum, exclude) {
    let r;
    do {
        r = Math.floor(Math.random() * mainNum) + 1;
    } while(exclude.includes(r))
    return r;
}

console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
console.log(myRandom(50, [4, 7, 20, 35]));
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