I have one array like this:
var arr 1 = ["a", "b", "c", "d"];
How can I randomize / shuffle it?
I have one array like this:
var arr 1 = ["a", "b", "c", "d"];
How can I randomize / shuffle it?
Credit goes here.
function fisherYates ( myArray ) {
var i = myArray.length;
if ( i == 0 ) return false;
while ( --i ) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var tempi = myArray[i];
var tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
Some more info about the algorithm used.
One implementation:
["a", "b", "c", "d"].sort(function() { return Math.floor(Math.random()*3 -1)});
[Edit] Much simpler implementation from here.
["a", "b", "c", "d"].sort(function() { return 0.5 - Math.random();});