I have an array like this:
var arr1 = ["a", "b", "c", "d"];
How to play randomly?
#1 building
A person can (or should) use it as an Array prototype:
From ChristopheD:
Array.prototype.shuffle = function() { var i = this.length, j, temp; if ( i == 0 ) return this; while ( --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); temp = this[i]; this[i] = this[j]; this[j] = temp; } return this; }
#2 building
This is Durstenfeld shuffle JavaScript implementation of, Durstenfeld shuffle Is a computer optimized version of Fisher Yates:
/** * 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; } }
The Fisher Yates algorithm works by selecting a random element for each original array element and then excluding it from the next drawing. It's like picking at random from a deck of cards.
This exclusion is ingenious (invented by Durstenfeld for use by computers) by exchanging the selected element with the current one, and then selecting the next random element from the rest. For best efficiency, the loop runs backward, simplifying random selection (it can always start at 0), and skipping the last element because there are no other choices.
The running time of the algorithm is O (n). Note that random playback is done in place. Therefore, if you do not want to modify the original array, use. slice(0) to copy it first.
Update to ES6 / ECMAScript 2015
The new ES6 allows us to assign two variables at a time. This is especially handy when we want to swap the values of two variables, because we can do it in one line of code. This is an abbreviation for the same feature 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]]; } }
#3 building
Use the basercore.js library. In this case, the method. shuffle() is appropriate. This is an example of this method:
var _ = require("underscore"); var arr = [1,2,3,4,5,6]; // Testing _.shuffle var testShuffle = function () { var indexOne = 0; var stObj = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5 }; for (var i = 0; i < 1000; i++) { arr = _.shuffle(arr); indexOne = _.indexOf(arr, 1); stObj[indexOne] ++; } console.log(stObj); }; testShuffle();
#4 building
Add to @Laurens Holsts answer. This is 50% compressed.
function shuffleArray(d) { for (var c = d.length - 1; c > 0; c--) { var b = Math.floor(Math.random() * (c + 1)); var a = d[c]; d[c] = d[b]; d[b] = a; } return d };
#5 building
var shuffle = function(array) { temp = []; originalLength = array.length; for (var i = 0; i < originalLength; i++) { temp.push(array.splice(Math.floor(Math.random()*array.length),1)); } return temp; };