How to mix an array in JavaScript?

4

In PHP, when I need to mix an array, I use the shuffle function.

So:

$a = array('@wallacemaxters', '@rray', '@CiganoMorrisonMendez');

shuffle($a);

print_r($a);

output:

Array
(
    [0] => @CiganoMorrisonMendez
    [1] => @wallacemaxters
    [2] => @rray
)

Similarly, I need to mix an array in JavaScript. But I did not find a Array method to do that.

How can I mix a Array in JavaScript?

    
asked by anonymous 26.10.2015 / 16:57

4 answers

8

Curious no one mentioned the Fisher-Yates , which is perhaps the most classic algorithm for to exchange a finite set. What is most interesting is that all possible returns of the algorithm are equally likely.

Here you can read an interesting article that shows how to build this algorithm, from pseudo-code to a result of complexity O (n) (you can read more about complexity here ).

For the TL; DR , the final implementation of the algorithm is

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}
    
26.10.2015 / 17:57
3

You can do this:

function shuffle(o) {
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o;
}

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

I found in jsfromhell

    
26.10.2015 / 17:02
2

Using the @GabrielRodrigues answer, I was able to get a result using the sort function.

So:

a = ['@wallace', '@rray', '@cigano']

a.sort(function (a, b){ 
  return Math.floor(Math.random() * 10);
});

console.log(a);
    
26.10.2015 / 17:07
1

Using refer to underscorejs.com :

Array.prototype.shuffle = function() {
  var set = this;
  var length = set.length;
  var shuffled = Array(length);
  for (var index = 0, rand; index < length; index++) {
    rand = Math.floor(Math.random() * (index - 1));
    if (rand !== index) shuffled[index] = shuffled[rand];
    shuffled[rand] = set[index];
  }
  return shuffled;
};


ary = ['@wallacemaxters', '@rray', '@CiganoMorrisonMendez'];
console.log(ary.sfuffle());
    
26.10.2015 / 17:04