Unique Random Values From Array Of Unique Values Javascript
Solution 1:
Just for the sake of simplicity I will assume your elements have a class.
So, I would grab all elements:
var elements = document.getElementsByClassName("square");
Then I would create an array with the IDs
var ids = [];
for (var i = 0; i < elements.length; ++i)
{
ids.push(elements[i].getAttribute("id"));
}
And then generate random numbers on the length of the array
var random = roundingFunction(Math.random() * ids.length);
Then retrieve the element at the index and remove from the array
var elementID = ids.splice(random, 1);
And repeat.
Solution 2:
There are bascially three different approaches:
- Pick an item by random and repeat if it was used before.
- Put all items in an array, pick by random and remove from the array.
- Put all items in an array and shuffle.
Which one would be the most efficient can't be answered in the scope of your question. The difference between them is so small that it negligible considering how much the performance differs between browsers.
If you really need the most efficient, you have to try them all and test the performance in a wide variety of browser.
Otherwise just pick the one that seems easiest to implement. The are all good enough for any normal application.
Post a Comment for "Unique Random Values From Array Of Unique Values Javascript"