Random Items From Array

by the_voder

JavaScript

$(document).ready(function() {
    
    // Prefix to prepend to image name
    var prefix = "img";
    
    // Array of image names
    var images = new Array(
        "image1.jpg",
        "image2.jpg",
        "image3.jpg",
        "image4.jpg",
        "image5.jpg",
        "image6.jpg",
        "image7.jpg",
        "image8.jpg",
        "image9.jpg",
        "image10.jpg"
    );
    
    // Function returns random array element
    function randomElement() {
        // Pick random index
        var rand = Math.round(Math.random() * (images.length - 1));
        // Pick element from array based on random index
        var element = images[rand];
        // Remove picked element from array
        images.splice(rand, 1);
        // Return picked element
        return element;
    }
    
    // Get random items from array
    var img1 = prefix + '/' + randomElement();
    var img2 = prefix + '/' + randomElement();
    
    console.log(img1 + ', ' + img2);
});