Marc Ster
Marc Ster

Reputation: 2316

Javascript get random variables from array but each just once

I´d like to get random variables from a javascript and prepend it to a div container like that:

// my Array
var thumbnailArray = new Array();
thumbnailArray[0] = 'contentarray1';
thumbnailArray[1] = 'contentarray2';
thumbnailArray[2] = 'contentarray3';


function thumbnailquery () {
for (var i = 0; i <= 3; i++) {
$('#myDiv').prepend(thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)])
}
}

Now how can i ensure that each variable is only taken once but still randomly?

Thank You

Upvotes: 1

Views: 1273

Answers (4)

Geoffrey Burdett
Geoffrey Burdett

Reputation: 1976

Use splice() http://www.w3schools.com/jsref/jsref_splice.asp

randNum = thumbnailArray[Math.floor(Math.random() * thumbnailArray.length)]
$('#myDiv').prepend(splice(randNum,1))

Upvotes: 1

adeneo
adeneo

Reputation: 318162

Shuffle the array and pop of values instead

function shuffle(a) {
  var c=a.length,t,r;
  while (0 !== c) {
    r = Math.floor(Math.random() * c);
    c -= 1;t = a[c];a[c] = a[r];a[r] = t;
  }
  return a;
}

var thumbnailArray = [
    'contentarray1',
    'contentarray2',
    'contentarray3'
];

shuffle( thumbnailArray );
thumbnailquery();

function thumbnailquery () {
    for (var i = 0; i <= 3; i++) {
       $('#myDiv').prepend( thumbnailArray.pop() );
    }
}

FIDDLE

Upvotes: 3

isick
isick

Reputation: 1487

There's no elegant way to do it the way you describe. You could construct an array of "selected indices" and ensure that each random number didn't already exist in that array, but that has a worst case operating time of infinity so highly not recommended.

Your best bet would be to shuffle the array and then iterate over, selecting the elements in order (shuffled order).

See this Stack Overflow for a good way to shuffle an array in JavaScript How can i shuffle an array in JavaScript?

Upvotes: 1

Ramzi Khahil
Ramzi Khahil

Reputation: 5052

Copy the array. Then delete objects that you took from the copied array.

Upvotes: 1

Related Questions