Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda