One aspect that hasn't been addressed is the reason why your current solution is failing or why rearranging your array might be a better option. Your current code simply generates a random index to access elements in the array, similar to rolling a die where repeats are more likely than getting unique numbers each time. This randomness is key to (pseudo-)random number generation, ensuring unpredictable results.
To retrieve elements from the array randomly without repeating, you need to prevent duplicates intentionally. Two effective ways to achieve this are:
1) Shuffling the array and iterating through it as suggested in the comments of your question.
2) Removing accessed elements from the array and looping until it's empty.
Shuffling the array stands out as the preferred method since it doesn't alter or destroy the original array like removing elements does. Here's why shuffling works while your initial approach doesn't:
Shuffling maintains the original elements but in a randomized order, much like shuffling a deck of cards. As you go through the shuffled list, there's no chance of encountering a card twice.
On the other hand, removing items from the sorted array ensures each picked element is unique, preventing duplicates. As long as an item is removed from the array after being selected, you won't encounter it again.
Your current method involves selecting a random card from a sorted deck, looking at it, and returning it to its original place before picking another - increasing the likelihood of revisiting the same card.
The recommended approach involves using the Fisher-Yates shuffle function mentioned in the comments:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
You can implement it like this:
myarray = [ ... ];
myarray = shuffle(myarray);
function addSomeImages(limit) {
for (var i = lastIdx; i < lastIdx + limit; i++) {
$('#endless-gallery').append('<a data-fancybox="gallery" href="' + myarray[i].big + '"><img class="photo" src="' + myarray[i].thumb + '" /></a>');
}
}