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
.
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>
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.
//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 );
}