Shuffle an array in-place using Fisher–Yates shuffle
var shuffle = function(a,b,c){for(b=a.length;b;c=0|b*Math.random(),a[c]=[a[--b],a[b]=a[c]][0]);}
var a = [1, 2, 3, 4, 5, 6, 7];
shuffle(a); console.log(a);
// [2, 3, 6, 7, 4, 1, 5]
shuffle(a); console.log(a);
// [3, 6, 5, 2, 1, 4, 7]
@vjeux, I'm sorry, I don't understand. The version
function c(a){return a.pop?a.sort(c):Math.random()-.5}
does shuffle the inner arrays, but not the outer one (because of the invalid value). Callingvar a=[[1,2],[3,4],[5,6]]; a=shuffle(a);
changes the array to[[2,1],[4,3],[5,6]]
, for example, no matter if it's called with or withouta=
. My version always returns a random number and therefor shuffles the outer array too. But it's a bad implementation anyway, it's not worth the trouble for saving a single byte. ;-)