Barney
Barney

Reputation: 1848

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)];
      }

Upvotes: 3

Views: 1501

Answers (3)

nabrown
nabrown

Reputation: 836

Based on @alexey-prokhorov's answer but using a different method for shuffling the array, you could do something like:

var getRandosFromArray = function(array, numRandos){
  var shuffled = shuffle(array)
  var randos = shuffled.slice(0, numRandos)
  return randos
}

// https://bost.ocks.org/mike/shuffle/
var shuffle = function(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

That way you have a generic function to which you can just pass an array and the number of random items (which are returned in an array) you want back from it.

Upvotes: 0

Raja Asthana
Raja Asthana

Reputation: 2100

You can do it like,

var arr = [1,2,3,4,4,5,8];
var randomValue = [];
for(i=arr.length; i>=0; i--) {
  var randomNum = Math.floor(Math.random() * i);
  randomValue.push(arr[randomNum]);
  if(i==arr.length-1)break;
}
console.log(randomValue);

Hope it helps.

Upvotes: 0

Alexey Prokhorov
Alexey Prokhorov

Reputation: 3921

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

Upvotes: 6

Related Questions