0

I am trying to randomize a Javascript array containing HTML elements. Here's what I have so far, but unfortunately I still get several duplicates afterwards. I don't see what's wrong about this snippet of code. Any ideas, anyone?

function randomizeArray(theArray)
        {
            var result = new Array();
            var randomNr;
            while ( theArray.length>0 )
            {
                randomNr = Math.floor( (Math.random() * theArray.length) );
                result.push( theArray[randomNr] );
                theArray.splice( randomNr, 1);
            }
            return result;
        }

Edit: After further review, this code appeared to work as intended when I tested it with an array of numbers. For some reason I still got duplicates with my array of

  • elements. Instead of putting the elements themselves in the array, I used the .html() of the elements. After that small modification everything suddenly worked as intended. I still don't know why that is, but at least it does work :)
  • Jort
    • 1,401
    • 8
    • 23
    • 39
    • Are you looking for corrections to your code, or the generally accepted way of randomizing an array in JavaScript? – j08691 Jun 26 '12 at 15:39
    • 2
      If you don't want duplicates, either test the yet present values or build a non randomized array that you may [shuffle](http://stackoverflow.com/questions/7070054/javascript-shuffle-html-list-element-order) afterwards. – Denys Séguret Jun 26 '12 at 15:41
    • random doesn't mean without duplicates. can you guarantee different results for two coin flips? – xvatar Jun 26 '12 at 16:39
    • I figured since I'm picking a random number, then pushing the item at that index to another array, and removing the same item from the main array there couldn't be any duplicates since the item will be removed from the array at the next iteration of the while loop. Am I missing something here? – Jort Jun 26 '12 at 17:46
    • My original post was a bit unclear perhaps. I want to randomise the indexes of the array items, so that when I print them out with a for loop I have the same items, just in a different order, with no duplicates. If possible I'd like my above code corrected, since I have no idea why it won't work.. – Jort Jun 26 '12 at 17:52

    2 Answers2

    1

    Check the top answer on this post: Random number in a loop

    Different language, but the theory is the same. The seed number used by the Math.random() will be the same every time and cause patterns to arise, which in turn will produce the duplicates you are getting.

    Community
    • 1
    • 1
    zakparks31191
    • 919
    • 2
    • 21
    • 42
    0

    The code worked as intended, the problem was my array containing objects of elements. As soon as I converted those objects to the corresponding html, and used those as items in my array, everything worked just great.

    Jort
    • 1,401
    • 8
    • 23
    • 39