If there is an array like this:
var arr1 = ["a", "b", "c", "d"];
How to randomly disrupt the order of the array, that is, shuffle it.
There is a simple random algorithm that is widely spread:
function RandomSort (a,b){ return (0.5 - Math.random()); }Actually, it is proved that the above is not completely random.
I just searched for too many such things on the Internet. Let’s take a look at a high-scoring answer on stackoverflow. The answer comes from github.
knuth-shuffle
The Fisher-Yates (aka Knuth) shuffle for Browser and Node.JS
Let’s take a look at the algorithm mentioned above. The code is as follows:
/*jshint -W054 */(function (exports) {'use strict';// http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-arrayfunction shuffle(array) {var currentIndex = array.length, temporaryValue, randomIndex;// While there remains elements to shuffle...while (0 !== currentIndex) {// Pick a remaining element...randomIndex = Math.floor(Math.random() * currentIndex);currentIndex -= 1;// And swap it with the current element.temporaryValue = array[currentIndex];array[currentIndex] = array[randomIndex];array[randomIndex] = temporaryValue;}return array;}exports.knuthShuffle = shuffle;}('undefined' !== typeof exports && exports || 'undefined' !== typeof window && window || global));The author recommends using a browser writing method:
(function () {'use strict';var a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = window.knuthShuffle(a.slice(0));console.log(b);}());Nodejs:
npm install -S knuth-shuffle(function () {'use strict';var shuffle = require('knuth-shuffle').knuthShuffle, a = [2,11,37,42], b;// The shuffle modifies the original array// calling a.slice(0) creates a copy, which is assigned to bb = shuffle(a.slice(0));console.log(b);}());There are other ones that are deformed from this algorithm, such as the following for loop. I won’t talk about anything else.
/*** Randomize array element order in-place.* Using Durstenfeld shuffle algorithm.*/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;}return array;}Using ES2015 (ES6)
Array.prototype.shuffle = function() {let m = this.length, i;while (m) {i = (Math.random() * m--) >>> 0;[this[m], this[i]] = [this[i], this[m]]}return this;}use:
[1, 2, 3, 4, 5, 6, 7].shuffle();
I found a lot of random algorithms for Chinese search, but whether it is completely random is still necessary, and efficiency and compatibility are still to be investigated. It is recommended that if you need to use randomly disrupt array elements later, you can use the above one.