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

117
Visualizações
Getting 2 unique values from array

I have the following task - form array of values I need to pick 2 values which are not equal. I want to make it with if / loop logic to understand the basis. I've succeed with my task but my loop seems to me doesn't over and the page after several refresh crash down.

We'll be very appreciate for help with my code.

var arrP = [];
var randomPersons = 2;
var nsm = ["Value 1", "Value 2", "Value 3", "Value 4", "Value 5"];
function randomGen() {
  for (i=0; i<randomPersons; i++) {
    var rnd = Math.floor(Math.random() * (nsm.length));
    arrP.push(rnd);
  }
}

do {
  randomGen();
}

    while (arrP[0] === arrP[1]);

document.write(nsm[arrP[0]] + "<br>" + nsm[arrP[1]]);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>

</body>
</html>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A rather naive implementation might be something like this. (Something more optimized would not need to modify the input array, for instance.)

It assumes that the arr is a "bag" of choices and doesn't really look at equality at all. In other words, if your "bag" is ["John", "John", "Peasoup", "Booze", "Scaffold"], it's possible to get two Johns in the output.

function pickRandom(arr, num) {
  const output = [];
  const input = [...arr]; // shallow-copy so we can modify it
  // work to do and choices to pick?
  while(input.length > 0 && output.length < num) {
    // Pick random remaining index...
    const index = Math.floor(Math.random() * input.length);
    const [pick] = input.splice(index, 1); // Remove from input
    output.push(pick); // ... put into output
  }
  return output;
}

var picks = pickRandom(["Value 1", "Value 2", "Value 3", "Value 4", "Value 5"], 2);
document.getElementById("x").value = JSON.stringify(picks, null, 2);
<textarea id="x" rows="10" cols="30"></textarea>

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