Wednesday, June 1, 2011

JavaScript array shuffle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * @function
 * @param {Boolean} $new Need a new array or shuffle this.
 * @return {Array}
 * @author Alexey Bass (albass)
 */
Array.prototype.shuffle = function($new) {
    $new = $new || false;
     
    var $a = !$new ? this : this.slice()
    ,   $len = $a.length, $i = $len
    ,   $p, $t;
     
    while ($i--) {
        $p = parseInt(Math.random() * $len);
        $t = $a[$i], $a[$i] = $a[$p], $a[$p] = $t;
    }
     
    return $a;
};

Also on GitHub

1 comment: