DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Generating A Shuffled Array.

01.08.2006
| 9370 views |
  • submit to reddit
        Adds a method to Array to return a shuffled version of the array.

if (!Array.prototype.shuffle) {
    Array.prototype.shuffle = function() {
        // Clone this array.
        var result = this.concat();

        // Swap each element with another randomly selected one.
        for (var i = 0; i < result.length; i++) {
            var j = i;
            while (j == i) {
                j = Math.floor(Math.random() * result.length);
            }
            var contents = result[i];
            result[i]    = arr[j];
            result[j]    = contents;
        }

        return result;
    };
}
    

Comments

Snippets Manager replied on Fri, 2010/08/27 - 5:06am

the above gives following error Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET4.0C; .NET4.0E; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Timestamp: Fri, 27 Aug 2010 09:09:08 UTC Message: 'arr' is undefined Line: 151 Char: 13 Code: 0 --------------------------------------------------------------------------------- modified version if (!Array.prototype.shuffle) { Array.prototype.shuffle = function() { // Clone this array. var result = this.concat(); var arr=this; // Swap each element with another randomly selected one. for (var i = 0; i < result.length; i++) { var j = i; while (j == i) { j = Math.floor(Math.random() * result.length); } var contents = result[i]; result[i] = arr[j]; result[j] = contents; } return result; }; }