The most efficient shuffler array

How can I shuffle array values ​​in the most efficient way?

Each element is just a line containing HTML.

+5
source share
4 answers

You have several options.

First, you can use a stupidly naive sorter ...

arr = arr.sort(function() { return Math.random() - .5 }); 

jsFiddle .

It's quick and dirty, but often considered bad practice.

Further reading .

The best way to randomly sort Array is through a Fisher-Yates shuffle .

 var newArr = []; while (arr.length) { var randomIndex = Math.floor(Math.random() * arr.length), element = arr.splice(randomIndex, 1) newArr.push(element[0]); } 

JSBin .

+6
source

This is the one I use. It gives a random number for each element, sorts the array by these random numbers (moving the real values ​​along), and then deletes the random numbers again. It seems to be evenly distributed, but I have not yet mathematically proven this.

 arr = arr.map(function(v) { return [v, Math.random()]; }).sort(function(a, b) { return a[1] - b[1]; }).map(function(v) { return v[0]; }); 

http://jsfiddle.net/XQRFt/ - Test results (may be slow)

+2
source

Let me post my own answer to convince you NOT to use the random sort() method, as it will not give a very random result.

As already mentioned, Fisher-Yates shuffle is the most efficient algorithm for this purpose and is easy to implement using the following ES6 code:

 const src = [...'abcdefg']; const shuffle = arr => arr.reduceRight((r,_,__,s) => (r.push(s.splice(0|Math.random()*s.length,1)[0]), r),[]); console.log(JSON.stringify(shuffle(src))); 
 .as-console-wrapper {min-height:100%} 

+1
source

This is my solution for shuffling an array:

  function shuffle(array) { var resultArray = new Array(); for(i=0;i<array.length;i++) { var randomEle = Math.floor(Math.random()*array.length); resultArray.push(array[randomEle]); array.splice(randomEle,1); } resultArray = resultArray.concat(array); return resultArray; } 

This is a random competition to compare my method with others 2

http://jsperf.com/shuffle-contest/2

0
source

All Articles