# Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript [1,2,3,4,5,6,7,8,9].shuffle()

• This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
• Author
Posts
• #46565

Make this code work:

``````[1,2,3,4,5,6,7,8,9].shuffle()
// [2, 4, 1, 8, 9, 6, 5, 3, 7]
``````

Can somebody help? It seems I have to use prototype an maybe Math.randam(). Thanks

#143795

It’s from Object-oriented Javascript by Stoyan Stefanov, great book.

#143797

before sleep was that

``````Array.prototype.shuffle = function() {
var len = this.length;
for ( var i = 0; i < len; i++ ) {
var ele = this*, pos = this[Math.floor(Math.random()*len)];
if(pos == undefined) {
pos = ele;
}
}
return this;
};
``````
#143833

Give me, please some tips, here my result (don’t want to look at Stock overflow, I know there is answer, want to properly uderstand):

Array.prototype.shuffle = function() {
var len = this.length,
shuffleArr = [];

for ( var i = 0; i < len; i++ ) {
var elem = this,
pos = Math.floor( Math.random() * len );

if ( shuffleArr[pos] == undefined) {
shuffleArr[pos] = elem
shuffleArr.push(elem);
}

}

return shuffleArr;
}

var a =[1,2,3,4,5,6,7,8,9];

a.shuffle()

#143864

It’s nice solution **shuffleArr.splice(pos, 0, elem);** I didn’t know how to make that elem go to different position, because Math.random() can repeat themselves, thats why there was this strange

if ( shuffleArr[pos] == undefined)

but, why you use:

pos = Math.floor( Math.random() * (shuffleArr.length + 1) )

this works too:

pos = Math.floor( Math.random() * len );