Shuffle / Randomize Array items in JavaScript

Marius
Posts: 55

Shuffle / Randomize Array items in JavaScript

Hello
How can I shuffle /randomize an array in JavaScript? Is there a JavaScript function like shuffle() in PHP?

Admin
Hi
You can use this function:

Code: Select all

// receive an array and return it with the items shuffled /randomized
function shuffle(ar){
  for(var j, x, i = ar.length; i; j = Math.floor(Math.random() * i), x = ar[--i], ar[i] = ar[j], ar[j] = x);
  return ar;
}

- If you want to see an example and to test it, visit this page: http://coursesweb.net/javascript/shuffle-randomize-array_cs

Adv. Posts: 01

Similar Topics