1

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

2
  • 1
    Do you have to leave the element in the array? If not, you could remove it from the array after it's been selected. Commented Dec 10, 2013 at 19:58
  • hm it would be better if it would stay in there Commented Dec 10, 2013 at 20:06

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

1

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?

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.