Over a million developers have joined DZone.

Generating A Shuffled Array.

·
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;
    };
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}