Saturday, August 21, 2010

Random array sort in Javascript

There is such an array method called sort, which puts up the elements of an array in alphabetical order, changing it (without copying the whole array). Additionally, it takes also one function parameter for defining the order of elements. If it returns negative number, given elements will be switched, and when positive one, nothing will happen. So to sort an array in random order, it just need to return random numbers in -1 to 1 range.
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
a.sort(function(){ return Math.random()-0.5; });
//'a' is now something like
//[9, 0, 2, 3, 4, 1, 8, 5, 6, 7]
From the other hand, it is only one week to the NodeKnockout. I'm really looking forward for this!

5 comments:

  1. As I learned myself, this method will never be truly random. The example results shown would never happen, where the 9 becomes first. This method only moves the array elements to nearby positions.

    See this article http://javascript.about.com/library/blsort4.htm

    ReplyDelete
  2. This article gives a nice demo of the problem with random sorting using the array.sort() function

    http://sroucheray.org/blog/2009/11/array-sort-should-not-be-used-to-shuffle-an-array/

    ReplyDelete
  3. Thanks for your post.Under hypnosis, you can become desensitized to your fears, safely and comfortably, beginning with the most subtle unconscious cues that set them off.

    Hypnosis Hong Kong

    ReplyDelete