web-dev-qa-db-fra.com

Obtenir une valeur aléatoire d'un tableau JavaScript

Considérer:

var myArray = ['January', 'February', 'March'];    

Comment puis-je sélectionner une valeur aléatoire de ce tableau en utilisant JavaScript?

581
Sarah
var Rand = myArray[Math.floor(Math.random() * myArray.length)];
1138
Jacob Relkin

J'ai trouvé encore plus simple d'ajouter une fonction prototype à la classe Array:

Array.prototype.randomElement = function () {
    return this[Math.floor(Math.random() * this.length)]
}

Maintenant, je peux obtenir un élément de tableau aléatoire en tapant simplement:

var myRandomElement = myArray.randomElement()

Notez que ceci ajoutera une propriété à tous les tableaux. Ainsi, si vous utilisez une boucle utilisant for..in, vous devriez utiliser .hasOwnProperty():

for (var prop in myArray) {
    if (myArray.hasOwnProperty(prop)) {
        ...
    }
}

(Cela peut ou peut ne pas être un problème pour vous.)

78

Si vous avez déjà underscore ou lodash dans votre projet, vous pouvez utiliser _.sample .

// will return one item randomly from the array
_.sample(['January', 'February', 'March']);

Si vous devez obtenir plusieurs éléments au hasard, vous pouvez le passer comme second argument sous soulignement:

// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);

ou utilisez la méthode _.sampleSize dans lodash:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
51
Brendan Nee

Supposons que vous souhaitiez choisir un élément aléatoire différent de la dernière fois (pas vraiment aléatoire, mais toujours une exigence commune) ...

En nous appuyant sur la réponse de @Markus, nous pouvons ajouter une autre fonction prototype:

Array.prototype.randomDiffElement = function(last) {
   if (this.length == 0) {
      return;
   } else if (this.length == 1) {
      return this[0];
   } else {
      var num = 0;
      do {
         num = Math.floor(Math.random() * this.length);
      } while (this[num] == last);
      return this[num];
   }
}

Et mettre en place comme ça:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)
19
CrazyTim

Méthode prototype

Si vous envisagez d’obtenir beaucoup de valeurs aléatoires, vous pouvez définir une fonction. 

Tout d'abord, mettez ceci dans votre code quelque part:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

À présent:

[1,2,3,4].sample() //=> a random element

Code publié dans le domaine public selon les termes de la licence CC0 1.0 .

18
Ben Aubin

La version la plus courte:

var myArray = ['January', 'February', 'March']; 
var Rand = myArray[(Math.random() * myArray.length) | 0]
9
foxiris

~~ est beaucoup plus rapide que Math.Floor(); ainsi, lorsqu'il s'agit d'optimiser les performances tout en produisant une sortie à l'aide d'éléments d'interface utilisateur, ~~ remporte la partie. PLUS D'INFORMATIONS

var Rand = myArray[~~(Math.random() * myArray.length)];

Mais si vous savez que le tableau contiendra des millions d’éléments, vous devrez peut-être reconsidérer entre Bitwise Operator et Math.Floor(), étant donné que les opérateurs au niveau du bit se comportent étrangement avec des nombres importants. Voir l'exemple ci-dessous expliqué avec la sortie. PLUS D'INFORMATIONS

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343
8
Ankur Soni

Si vous avez des valeurs fixes (comme une liste de noms de mois) et souhaitez une solution sur une ligne

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

La deuxième partie du tableau est une opération d'accès telle que décrite dans Pourquoi [5,6,8,7] [1,2] = 8 en JavaScript?

7
I.G. Pascual

Le prototype d'édition de tableau peut être dangereux. Ici, c’est une fonction simple pour faire le travail.

function getArrayRandomElement (arr) {
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  // The undefined will be returned if the empty array was passed
}

Usage:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);
3
Seagull

Si vous souhaitez l'écrire sur une ligne, comme la solution de Pascual, une autre solution consisterait à l'écrire à l'aide de la fonction de recherche de ES6 (sur la base du fait que la probabilité de sélectionner au hasard l'un des éléments n est 1/n):

var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);

Utilisez cette approche à des fins de test et s’il existe une bonne raison de ne pas enregistrer le tableau dans une variable distincte uniquement. Sinon, utilisez les autres réponses (floor(random()*length et en utilisant une fonction distincte).

3
Stephan

Ceci est similaire, mais plus général, à la solution de @Jacob Relkin:

Ceci est ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

Le code fonctionne en sélectionnant un nombre aléatoire compris entre 0 et la longueur du tableau, puis en renvoyant l'élément à cet index.

2
Max Heiber

Fonction récursive, autonome, pouvant renvoyer n'importe quel nombre d'éléments (identique à lodash.sampleSize ):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.Push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}
2
dwilt

Fonction simple:

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
2
Dhakshith

J'ai trouvé un moyen de contourner les complications de la réponse, en concaténant simplement la variable Rand avec une autre variable permettant d'afficher ce nombre dans l'appel de myArray []; En supprimant le nouveau tableau créé et en évitant ses complications, j'ai trouvé une solution efficace:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var myArray = ['January', 'February', 'March', 'April', 'May'];    

var Rand = Math.floor(Math.random() * myArray.length);

var concat = myArray[Rand];

function random() {
   document.getElementById("demo").innerHTML = (concat);
}
</script>

<button onClick="random();">
Working Random Array generator
</button>

</body>
</html>
1
FaverosGema

static generateMonth() { 
const theDate = ['January', 'February', 'March']; 
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};

Vous définissez une variable constante dans le tableau, vous avez ensuite une autre constante qui choisit de manière aléatoire entre les trois objets du tableau et la fonction renvoie simplement les résultats.

1
Neil Meyer

Une manière générique d’obtenir des éléments aléatoires:

let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
let months = random_elems(some_array, 3);

console.log(months);

function random_elems(arr, count) {
  let len = arr.length;
  let lookup = {};
  let tmp = [];

  if (count > len)
    count = len;

  for (let i = 0; i < count; i++) {
    let index;
    do {
      index = ~~(Math.random() * len);
    } while (index in lookup);
    lookup[index] = null;
    tmp.Push(arr[index]);
  }

  return tmp;
}

0
Rafael

Utiliser Faker.js :

const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);
0
Nathan

À mon avis, mieux que de jouer avec des prototypes ou de le déclarer juste à temps, je préfère l'exposer à window:

window.choice = function() {
  if (!this.length || this.length == 0) return;
  if (this.length == 1) return this[0];
  return this[Math.floor(Math.random()*this.length)];
}

Maintenant, n'importe où sur votre application, vous l'appelez comme ceci:

var Rand = window.choice.call(array)

De cette façon, vous pouvez toujours utiliser la boucle for(x in array) correctement

0
frankies

une autre méthode facile:

var myArray = ['keke','keko','cano','halo','zirto'];

var randomValue = myArray[Math.round((Math.random()*1000))%myArray.length];
0
Kamuran Sönecek