I'm looking to get two different random items from the same array in JS. There are relating questions on Stack Overflow but I fail to understand how the Fisher Yates Shuffle works. I need to search the whole array to retrieve these items, but the array is small in size.
Currently I have a while loop but this doesn't seem to be the most efficient way of acheiving:
var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"]; //Fake field names to dupe the bots!
var honeyPot = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array
var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array
while (honeyPot == honeyPot2)
{
var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)];
}
Just shuffle the array and get first two items:
var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"];
var results = honeyPots
.sort(function() { return .5 - Math.random() }) // Shuffle array
.slice(0, 2); // Get first 2 items
var honeyPot = results[0];
var honeyPot2 = results[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With