Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get two different random items from same array in JS

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)];
      }
like image 276
Barney Avatar asked Nov 25 '25 00:11

Barney


1 Answers

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];
like image 102
Alexey Prokhorov Avatar answered Nov 26 '25 13:11

Alexey Prokhorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!