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.
Marius
Posts: 107

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 Posts: 805
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: https://coursesweb.net/javascript/shuffl ... e-array_cs

Similar Topics