0

I have this array:

var numberArray = [1, 2, 3]

Using jQuery, what is the easiest way to loop through all elements in this array in a random order exactly once? Valid sequences are 3,2,1, 2,3,1, and invalid ones are 1,1,1, or 2,2,3.

yesman
  • 7,165
  • 15
  • 52
  • 117

2 Answers2

5

I'm not aware of a specific jQuery method to randomise, but you could sort the array into a random order then loop through.

$(function() {
    var numberArray = [1,2,3];
    numberArray.sort(function() {
        return 0.5 - Math.random();
    })
    $.each(numberArray, function(k,v) {
        $('div').append(v);
    })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Duncan Tidd
  • 1,140
  • 10
  • 13
1

This should do the trick for you. Right now the script just prints out each array value in the console from inside the JQuery each function but you can easily do whatever you need to from inside the $.each function. I didn't parseInt() the array values inside $.each loop so if you need them to have a type of number then you will have to do that.

Live Example

//The array to randomize
var numberArray = [1, 2, 3]

//sort the array randomly and convert it back to an array so 
//that you can get the value of object inside the each function.
var randomArray = numberArray.sort(randomSort).toString().split(",");

//loop through the random array
$.each(randomArray,function(){

     //log the value
     console.log(this);

 });

/* randomSort function */
function randomSort(a,b) {
    // Get a random number between 0 and 10
    var temp = parseInt( Math.random()*10 );

    // Get 1 or 0, whether temp is odd or even
    var isOddOrEven = temp%2;

    // Get +1 or -1, whether temp greater or smaller than 5
    var isPosOrNeg = temp>5 ? 1 : -1;

    // Return -1, 0, or +1
    return( isOddOrEven*isPosOrNeg );
}
Larry Lane
  • 2,141
  • 1
  • 12
  • 18
  • what is the point of converting to string and then converting back? – charlietfl Mar 19 '16 at 14:14
  • @charlietfl It was only to allow ohyeah to manipulate the object inside of the loop. – Larry Lane Mar 19 '16 at 14:24
  • Thanks for the answer, I did not know about the sort function. I have tried your answer and the one posted by Duncan, both seem to do the same. Is there any benefit to using your more complex looking randomizer over the other one? – yesman Mar 19 '16 at 14:29