Array shuffle with while loop - Node.js Array

Node.js examples for Array:Shuffle

Description

Array shuffle with while loop

Demo Code

Array.prototype.shuffle = function () {
    var currentIndex = this.length, temporaryValue, randomIndex;

    while (0 !== currentIndex) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;//from   w w  w .  ja  v  a  2  s. c om

        // And swap it with the current element.
        temporaryValue = this[currentIndex];
        this[currentIndex] = this[randomIndex];
        this[randomIndex] = temporaryValue;
    }
};

Related Tutorials