How to mix an array in Javascript?

Asked

Viewed 3,336 times

5

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

Thus:

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

shuffle($a);

print_r($a);

exit:

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

Likewise, I need to mix an array in Javascript. However, I couldn’t find a method for Array to do this.

How can I mix one Array javascript?

  • 1

    Isn’t there a native function for this in js? o.o

  • No, that’s why I asked

5 answers

10


Curious that no one mentioned the Fisher-Yates, which is perhaps the most classic algorithm for permuting a finite set. The most interesting thing is that all possible returns of the algorithm are equally likely (in English, the term for this is unbiased).

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

To 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;
}

4

You can do it like 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

2

Using as reference the 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());

  • 1

    In that particular case, we would depend on undescore.js. Thank you, because I use undescore in all my projects :)

2

Using the @Gabrielrodrigues response, I was able to get a result using the function sort.

Thus:

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

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

console.log(a);

0

Talk, guys, I wanted to share with you one of the infinite solutions =)

function shuffleArray(array = ["banana", "ovo", "salsicha", "goiaba", "chocolate"]) {
    const newArray = [];
    let number = Math.floor(Math.random() * array.length);
    let count = 1;
    newArray.push(array[number]);

    while (count < array.length) {
        const newNumber = Math.floor(Math.random() * array.length);
        if (!newArray.includes(array[newNumber])) {
            count++;
            number = newNumber;
            newArray.push(array[number]);
        }
    }

    return newArray;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.