Never been to DZone Snippets before?

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

Generating a shuffled array. (See related posts)

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;
    };
}

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts