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

150
Vistas
How to be sure that the next randomly selected value from an array is not the same as the current one using Javascript?

I am randomly selecting values from an array. I want to be sure that the next selected value is not the same as the current one. How can I implement this rule in Javascript?

const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);

This is a result of script. I want to avoid the same values next to each other like in the red circle.

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

0

You could filter pages removing current value and only after that select random element.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If the one you pick is the same as the previous one, pick a new one:

const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);

let random2;
// Pick a new one:
while (random == ( random2 = Math.floor(Math.random() * pages.length)));

This assumes every value in the array is different, so it just cares that the two indexes (random and random2) are different.

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