Rewritten title: Learn how to randomly sort (shuffle) a JavaScript array
P粉818125805
2023-08-21 11:28:39
<p>I have an array like this:</p>
<pre class="brush:php;toolbar:false;">var arr1 = ["a", "b", "c", "d"];</pre>
<p>How do I randomize/shuffle it? </p>
This is a JavaScript implementation of Durstenfeld shuffle, which is an optimized version of the Fisher-Yates algorithm:
It selects a random element for each original array element and excludes it from the next draw, just like drawing randomly from a deck of cards.
This clever elimination operation swaps the selected element with the current element, then selects the next random element from the remaining elements, looping backwards for optimal efficiency, ensuring that the random selection is simplified (it can always start from 0), thereby skipping the last element.
The running time of the algorithm is
O(n)
. Note that shuffling is done in-place, so if you don't want to modify the original array, create a copy first using.slice(0)
.Edit: Updated to ES6/ECMAScript 2015
The new ES6 allows us to assign two variables at the same time. This is especially convenient when we want to swap the values of two variables, as we can do it in one line of code. Here is a shorter form of the same function that uses this functionality.
In fact, the unbiased shuffling algorithm is Fisher-Yates (also known as Knuth) shuffling algorithm.
You can see a great visualization here (original post linked here )