Extract 4 random Strings from an Array in JavaScript

2

How could I extract 4 strings randomly from an array, for example this

var myArray = ["Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos", "Aceituna maceradas", 
           "Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos", "Banderillas", "Frutos secos",
           "Cacahuetes", "Mojitos" 
          ]

And that they were not repeated. Then I would put them in an .html

    
asked by Juan 07.09.2016 в 13:16
source

2 answers

3

Remove the positions that you have already chosen, so as not to modify the original array, create an array of positions and work with that. For example:

var myArray = ["Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos", "Aceituna maceradas",
  "Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos", "Banderillas", "Frutos secos",
  "Cacahuetes", "Mojitos"
];
var cuatroRandom = [];
var posicionesElegibles = [];
var i, r;
for (i = 0; i < myArray.length; i++) posicionesElegibles[i] = i;
for (i = 0; i < 4; i++) {
  r = Math.floor(Math.random() * posicionesElegibles.length);
  cuatroRandom.push(myArray[posicionesElegibles[r]]);
  posicionesElegibles.splice(r, 1);
}
console.log(cuatroRandom.toString());

I add an alternative method, it uses less memory since it only saves the positions already used to control that they do not happen again, but it is a bit slower since it searches inside the control matrix. Depending on the problem, one system or another may be more appropriate.

var myArray = ["Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos", "Aceituna maceradas", 
           "Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos", "Banderillas", "Frutos secos",
           "Cacahuetes", "Mojitos" 
          ];
	
var cuatroRandom=[];
var posicionesElegidas=[];
var i,j,r,c;
for (i = 0 ; i<4 ; i++){
	r = Math.floor(Math.random()*(myArray.length-posicionesElegidas.length))+1;
	c = 0;
	j = 0;
	do if (posicionesElegidas.indexOf(j++)==-1) c++; while(c<r);
	j--;
	cuatroRandom.push(myArray[j]);
	posicionesElegidas.push(j);
}
	console.log(cuatroRandom.toString());

A third method, which is a mixture of the two, and could be the fastest because it does not add or remove values in any array, and it would consume less memory than the first one because it saves booleans instead of positions, it would create an array of position control, initializing them all to true, and going off as they are used.

var myArray = ["Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos", "Aceituna maceradas", 
           "Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos", "Banderillas", "Frutos secos",
           "Cacahuetes", "Mojitos" 
          ];
	
var cuatroRandom=[];
var posicionesElegibles=[];
var posiciones=myArray.length;
posicionesElegibles.length=posiciones;
posicionesElegibles.fill(true);
var i,j,r,c;
var contadorElegidas=0;
for (i=0; i<4;i++){
	r=Math.floor(Math.random()*(posiciones-contadorElegidas))+1;
	c=0;
	j=0;
	do if (posicionesElegibles[j++])c++; while(c<r);
	j--;
	cuatroRandom.push(myArray[j]);
	posicionesElegibles[j]=false;
	contadorElegidas++;
}
	console.log(cuatroRandom.toString());
    
answered by 07.09.2016 / 13:36
source
1

I leave you other alternatives:

var myArray = [
  "Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos",   
  "Aceituna maceradas","Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos",
  "Banderillas", "Frutos secos","Cacahuetes", "Mojitos" 
];

function getRandomString(array){
  return array[Math.floor(Math.random()*array.length)]
}

function getRandomStrings(numero, array){
  var strings = [];
  while(strings.length < numero){
    var string = getRandomString(array);
    if(strings.indexOf(string) == -1) strings.push(string);
  }
  return strings;
}

console.log(getRandomStrings(4, myArray));

EDIT

Thanks to Arnau's comments, I give you another solution without using the while loop and taking in each loop the elements that have not yet been added:

var myArray = [
  "Rufles Original", "Aceitunas", "Lays al punto de sal", "Doritos TexMex", "Nachos",   
  "Aceituna maceradas","Rufles Jamon Jamon", "Cerveza", "Coca-cola", "Kas naranja", "Pepinillos",
  "Banderillas", "Frutos secos","Cacahuetes", "Mojitos" 
];


function getRandomStrings(number, array){
  var strings = [];
  for(var i = 0; i < number; i++){
    var validValues = array.filter(el => !strings.includes(el) );
    var rand = Math.floor(Math.random() * validValues.length);
    strings.push(validValues[rand])
  }
  return strings;
}

console.log(getRandomStrings(myArray.length - 1, myArray));
    
answered by 07.09.2016 в 14:15