More on Randomness of Arrays

A few months ago, I posted about how the classic method most JS programmers would use to randomise an array completely fails. I proposed a quick solution to it, but that solution had flaws of its own.

So, for those of you who need to shuffle decks of cards, scramble virtual eggs or just want to toss a little confusion into your applications, here’s a fully working array randomiser:

Array.randomiseArray = function(arr){
  var i, v;
  for (i=0; i<arr.length; i++) {
    v = arr[i];
    arr[i] = {
      v: v,
      sort: Math.random()
  arr.sort(function(a, b){
      return a.sort - b.sort;
  for (i=0; i<arr.length; i++) {
    arr[i] = arr[i].v;
  return arr;

One thought on “More on Randomness of Arrays

  1. Pingback: An Array of Random Thoughts | Doc Emmett Splendid's

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>