0

So there is an array of two different urls for images. My code calls for the array to be randomized and to put the randomized src in one of the img tags. Here is what it looks like:

var movieArray = ['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg'];
    var randomSrc1 = movieArray[Math.floor(Math.random() * movieArray.length)];
    var randomSrc2 = movieArray[Math.floor(Math.random() * movieArray.length)];
        $('#movie1_img').attr('src', '' + randomSrc1 + '');
        $('#movie2_img').attr('src', '' + randomSrc2 + '');

This works fine, but now there is the problem of having the two images being the same. I don't know how to prevent this. After the first src is given to the movie1_img tag do i need to delete that src from the array using .grep or something else?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Hanker
  • 53
  • 5

2 Answers2

0

Try using Array.prototype.slice() , Array.prototype.splice()

var movieArray = ['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg'];
// create copy of `movieArray`
var movies = movieArray.slice();
// get random item from within `movies`
var randomSrc1 = movies.splice(Math.floor(Math.random() * movies.length), 1);
// get remainding item from within `movies`
var randomSrc2 = movies.splice(0, 1);
guest271314
  • 1
  • 15
  • 104
  • 177
0

Shuffle the array instead:

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

var movieArray = shuffle(['http://gdj.gdj.netdna-cdn.com/wp-content/uploads/2011/12/grey-movie-poster.jpg', 'http://www.hollywoodreporter.com/sites/default/files/custom/Blog_Images/avengers-movie-poster-1.jpg']);
$('img[id^=movie][id$=_img]').attr('src', function(i){
    return movieArray[i];
});

-jsFiddle-

Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155