Shuffle array elements
by Nidhi Patel
JavaScript
var a = ['Nidhi','Rutu','Bhavya','Shweta'];
Array.prototype.shuffle = function(){
let len = this.length;
for(let i=0; i<len;i++){
let tmp = ''.concat(this[i]);
console.log('temporary:',tmp);
var pos = Math.floor(Math.random()*len);
let other = ''.concat(this[pos]);
console.log('others: ',other)
this[i]=other;
console.log(this[i]);
this[pos]=tmp;
console.log(this[pos]);
}
return this;
}
console.log(a.shuffle());
var num = ['Nidhi','Rutu','Bhavya','Shweta'];
Array.prototype.shuffle1=function(){
let len = this.length;
for(let i=0; i<len;i++){
let pos = Math.floor(Math.random()*i);
let tmp = this[pos];
this[pos]=this[i];
this[i]=tmp;
}
return this;
}
console.log(num.shuffle1());
//[9, 3, 6, 5, 4]
//[3, 5, 6, 9, 4]
//Â [3, 4, 6, 5, 9]
//[6, 4, 5, 3, 9]
//[3, 6, 4, 9, 5]
Array.prototype.shuffle2=function(){
let len = this.length;
for(let i=len-1; i>=0;i--){
let pos = Math.floor(Math.random()*(i+1));
let tmp = this[pos];
this[pos]=this[i];
this[i]=tmp;
}
return this;
}
console.log(num.shuffle2());