How to randomize the order of an array?
P粉512526720
P粉512526720 2023-10-11 18:42:00
0
2
466

I want to shuffle an array of elements in JavaScript like this:

[0, 3, 3] -> [3, 0, 3] [9, 3, 6, 0, 6] -> [0, 3, 6, 9, 6] [3, 3, 6, 0, 6] -> [0, 3, 6, 3, 6]


P粉512526720
P粉512526720

reply all (2)
P粉590428357

You can useFisher-Yates Shuffle(code adapted fromthis website):

function shuffle(array) { let counter = array.length; // While there are elements in the array while (counter > 0) { // Pick a random index let index = Math.floor(Math.random() * counter); // Decrease counter by 1 counter--; // And swap the last element with it let temp = array[counter]; array[counter] = array[index]; array[index] = temp; } return array; }
    P粉316110779

    Usesa modern version of the Fisher–Yates shuffling algorithm:

    /** * Shuffles array in place. * @param {Array} a items An array containing the items. */ function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; }

    ES2015 (ES6) version

    /** * Shuffles array in place. ES6 version * @param {Array} a items An array containing the items. */ function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }

    But be aware that usingdestructuring swap variables As of October 2017,allocations can incur severe performance penalties.

    use

    var myArray = ['1','2','3','4','5','6','7','8','9']; shuffle(myArray);

    Implement prototype

    UsingObject.defineProperty(Method taken from this SO answer) we can also implement the function as a prototype method for the array without having to have it appear in something likein a loop like for (i in arr). The following code will allow you to callarr.shuffle()to shuffle an arrayarr:

    Object.defineProperty(Array.prototype, 'shuffle', { value: function() { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } return this; } });
      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!