Javascript Array shuffle in-place





13
Date Submitted Mon. Oct. 2nd, 2006 1:05 PM
Revision 1 of 1
Beginner drench
Tags Array | JavaScript | List | Random | shuffle
Comments 3 comments
It works with Array types. The example is a simple list of numbers, but the array could contain anything; lists of strings, functions, DOM nodes, whatever. Unfortunately, a lot of things that seem like arrays in the DOM aren't really, so you can't shuffle the images on a page with just document.images.shuffle() all by itself.

(function () {                                                                 
    var swapper =                                                               
        function (a,L,e) {                                                     
            var r = Math.floor(Math.random()*L);                               
            var x = a[e];                                                       
            a[e] = a[r];                                                       
            a[r] = x;                                                           
        };                                                                     
    Array.prototype.shuffle =                                                   
        function () {                                                           
            var i,L;                                                           
            i = L = this.length;                                               
            while (i--) swapper(this,L,i);                                     
        };                                                                     
})();

// example

var x = [0,1,2,3,4,5,6,7,8,9];
x.shuffle();
 

D R

dren.ch/

Comments

Comments Um....
Mon. Oct. 9th, 2006 1:28 AM    Newbie phatcat
Comments Um....
Mon. Oct. 9th, 2006 1:36 AM    Newbie phatcat
  Comments Yep
Tue. Oct. 10th, 2006 8:40 PM    Beginner drench

Voting