Fisher-Yates shuffling array - Node.js Array

Node.js examples for Array:Shuffle

Description

Fisher-Yates shuffling array

Demo Code

/**/*w  w  w. j  a  va  2s  . c  om*/
 * Fisher-Yates shuffling
 *
 * @author http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling
 * @type   Array
 */
Array.prototype.shuffle = function ()
{
    var tmp, current, top = this.length;

    if (top)
    {
        while(--top)
        {
            current = Math.floor(Math.random() * (top + 1));
            tmp = this[current];
            this[current] = this[top];
            this[top] = tmp;
        }
    }

    return this;
};

Related Tutorials