Master the method of random sorting (shuffling) of arrays in JavaScript
P粉877719694
P粉877719694 2023-08-22 14:01:56
0
2
347
<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>
P粉877719694
P粉877719694

reply all(2)
P粉320361201

Here is a JavaScript implementation of Durstenfeld shuffle, which is an optimized version of Fisher-Yates:

/* 使用Durstenfeld shuffle算法原地随机排序数组 */
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

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.

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
P粉928591383

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 )

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

// Used like so
var arr = [2, 11, 37, 42];
shuffle(arr);
console.log(arr);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!