Unique random values from array of unique values javascript

I have twelve squares and six of those are selected randomly and a style then applied. This is achieved by generating random values from an array of unique values. The problem is the random values being generated aren't unique e.g 5 could be chosen more than once. I've looked at so many posts on here and there seems to be a number of different ways of achieving this - shuffling etc. Which would be the most effective?

   for (var i = 0; i < 6 ; i++)
    (function (i) {
      setTimeout(function () {
        var rand = arr[Math.floor(Math.random() * arr.length)];
        var square = document.getElementById('square' + rand);
        square.style.background = black;
    if (i == 6) Reset();
   }, 1500 * i);



Just for the sake of simplicity I will assume your elements have a class.

Example on jsFiddle

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)

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.


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.