Monday, 3 October 2011

How to Shuffle an Array in One Line

I often have to get a randomised version of an array, and I used to do it like this:

Create an empty array for the shuffled version
(Within a for loop) {
Get a random index using Math.floor(Math.random() * array.length)
Put the value from the unordered array into the ordered array, using the random index
Remove the value from the unordered array, again using the random index.
}

But now:

(Within a for loop) {
array.push(array.splice(Math.floor(Math.random() * array.length),1));
}

One line, no need for an empty array to be created.

No comments:

Post a Comment

Please enter your message here...