Wednesday, June 1, 2011

JavaScript array shuffle

/**
 * @function
 * @param {Boolean} $new Need a new array or shuffle this.
 * @return {Array}
 * @see http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function.htm
 * @see http://yelotofu.com/2008/08/jquery-shuffle-plugin/
 * @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