1

I'm using this to get a random item from my array (and append it to each list item)

   $('li').each(function(){
       var items = Array('the','and','to','a');
       var item = items[Math.floor(Math.random()*items.length)];
       $(this).append(item);
    });

I'm sure this is a quick thing but I don't really know where to look. How can I make sure there are no repeating items?

suryanaga
  • 3,728
  • 11
  • 36
  • 47
  • 1
    Maybe remove the item after getting it? This means that you need to declare `items` before the `each` loop. – XCS Sep 21 '13 at 11:15
  • possible duplicate of [jQuery math random number without repeating a previous number](http://stackoverflow.com/questions/6625551/jquery-math-random-number-without-repeating-a-previous-number) – Pointy Sep 21 '13 at 11:17

3 Answers3

2

Working Demo Here

you need to remove the used value from the array.

  var items = Array('the', 'and', 'to', 'a');
  $('li').each(function () {
      var randomNum = Math.floor(Math.random() * items.length)
      var item = items[randomNum];
      $(this).append(item);
      items.splice(randomNum, 1);
      
  });

Se your Demo on JsFiddle

Community
  • 1
  • 1
ReDEyeS
  • 851
  • 5
  • 16
1

Try

var items = new Array('the','and','to','a');
$('li').each(function(){
    var item = items.splice(Math.floor(Math.random() * items.length), 1);
    $(this).append(item);
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

So you want the elements randomized but not repeating? Then what you're looking for is a random permutation. If you want a quick'n'dirty solution, just randomly swap elements in your array. If you want a uniformly distributed random permutation, have a look at Eric Lippert's articles on the subject: http://ericlippert.com/2013/05/02/producing-permutations-part-six/

Tamás Zahola
  • 9,271
  • 4
  • 34
  • 46