Shuffle an array - Node.js Array

Node.js examples for Array:Shuffle

Description

Shuffle an array

Demo Code


shuffle: function(ary, typeNum) {
    for(var i = ary.length - 1; 0 <= i; i--) {
        if (typeNum == 'pretty'){
            var rnd = Math.random() * (i + 1) | 0;
            helper.swap(ary, i, rnd);//  w  w  w .j  a v  a2 s . co m
        } else {
            var rnd = Math.random() * i + 1 | 0;
            ary[i] = rnd;
        }
    }
},
swap: function(ary, a, b) {
    if(a < 0 || b < 0 || ary.length <= a || ary.length <= b) {
        throw new Error('IndexError ' + a + " - " + b);
    }
    var temp = ary[a];
    ary[a] = ary[b];
    ary[b] = temp;
},

Related Tutorials