Master the method of random sorting (shuffling) of arrays in JavaScript
P粉877719694
2023-08-22 14:01:56
<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>
Here is a JavaScript implementation of Durstenfeld shuffle, which is an optimized version of Fisher-Yates:
It selects a random element for each original array element and excludes it from the next draw, just like selecting randomly from a deck of cards.
This clever elimination method swaps the selected element with the current element, then selects the next random element from the remaining elements, looping backwards with optimal efficiency, ensuring that the random selection is simplified (it can always start from 0 start), thereby skipping the last element.
The running time of the algorithm is
O(n)
. It should be noted that this shuffling is performed in place, so if you do not want to modify the original array, please use the.slice(0)
method to make a copy first.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. This is a shorter form of the same function that uses this feature.
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 )