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

92
Visualizações
Picking Non-duplicate Random Numbers using JavaScript

How would I pick 5 random lottery numbers without having duplicate numbers? The code below is what I have so far and I just can't figure out where to insert the code to loop through to pick out duplicate numbers and reassign new numbers? I've tried adding if and else along with forEach function but it didn't work. This is the code I have so far. Thank you in advance.

let lotto = [];
    for(let i = 0; i < 5; i++){
      lotto[i] = Math.floor(Math.random() * 69) + 1;
    }

const sorting = lotto.sort((a,b) => a - b);
    console.log(sorting);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Two solutions:

  1. Create a list of your numbers, then pick (and remove) 5 from them.
  2. Create a loop that keeps generating numbers until it has 5 unique ones.

Your attempt can be adapted for solution 2:

let lotto = [];
while(lotto.length < 5) {
    console.log('Got', lotto.length, 'numbers!');
    // Changed 69 to 5 to "force" clashes (well, make it very likely)
    const num = Math.floor(Math.random() * 5) + 1;
    if (!lotto.includes(num)) lotto.push(num);
}

const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);

about 4 years ago · Juan Pablo Isaza Relatório

0

Considering the process will run at leats one time, the best solution is to use a do while loop and verify if this number already exist in the list.

const lotto = [];

do {
    const random = Math.floor(Math.random() * 69) + 1;
    if(!lotto.includes(random)) lotto.push(random);
} while(lotto.length < 5);

const sorting = lotto.sort((a, b) => a - b);
console.log(sorting);
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