How to shuffle an array

JavaScript polyfill, by , Saturday, March 8th, 2014

If you have an array, and you want it to be randomly shuffled, this is really easy;

  1. var num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  2. shuffledNum = num.sort(function () {
  3. return Math.random() - 0.5;
  4. });

The array shuffledNum now contains the same numbers that num does, but randomly shuffled. To better understand how this works, I recommend that you read How to use the Array sort method.