简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM