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

118
Vistas
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 Respuestas
Responde la pregunta

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 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