You need to create two functions.
The getRandomValue()
function will take the array as input and gives you the random index and the value.
function getRandomValue(myArray)
{
var index = Math.floor(Math.random() * myArray.length);
return [myArray[index], index];
}
Now you declare your images
and names
array.
var images = [{
"src": "images2/animal_1.jpg",
"title": "Dog"},
{
"src": "images2/animal_2.jpg",
"title": "Cat"},
{
"src": "images2/animal_3.jpg",
"title": "Sheep"},
{
"src": "images2/animal_4.jpg",
"title": "Cow"}];
var name = ["Dog", "Cat", "Sheep", "Cow"];
Now our main function comes here. First, get the random image by passing in the image array to the randomValue()
function. The same way do it for the names. Each value returned will be an array of the value and the index.
Now compare the index and if the indices are different, return both as an array. Else, return to the function to generate another.
function getImgName()
{
var img = getRandomValue(images);
var nam = getRandomValue(name);
if (img[1] != nam[1])
return getImgName();
else
return [img[0], nam[0]];
}