Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!