Shuffle / Randomize Array items in JavaScript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Posts: 106

Shuffle / Randomize Array items in JavaScript

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

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: ... e-array_cs

Similar Topics