RMH RMH - 2 months ago 9
jQuery Question

$.each, get 3 random objects from an array

I have the following fiddle using test data, and I am looking through data using $.each

I can loop through no problem, but I want to loop through the data, and then get 3 objects from it at random.

Any tips or tricks would help:

https://jsfiddle.net/inkedraskal/pah44qv6/

$.each(testData,function(x, blah){
//console.log(blah._id);

//this gets each objects id & picture, but I want to get 3 random objects, and their corresponding data
var activeValue = blah._id,
pictureValue = blah.picture;


var markUp = '';

markUp += activeValue + pictureValue;

console.log(markUp);
});


with the question below, they need to be unique**

Answer

We can create getRandomEntry() function which will return one of the array's elements by using Math.random() function. We'll create a loop which will take random entry every time it iterates.

function getRandomEntry() {
  return testData[Math.round(Math.random() * (testData.length - 1))];
}

for (var i=0; i<3; i++) {
  var entry = getRandomEntry();
  console.log(entry._id, entry.picture);
}

If you need an unique entry every time. You can keep random entries in separate array and check if new one is unqiue.

var randomEntries = [];

function getRandomEntry() {
  return testData[Math.round(Math.random() * (testData.length - 1))];
}

function entryExists(entry) {
  return randomEntries.indexOf(entry) > -1;
}

for (var i=0; i<3; i++) {
  var entry;

  do {

    entry = getRandomEntry();

  } while(entryExists(entry))

  randomEntries.push(entry);
  console.log(entry._id, entry.picture);
}