How to query a data in an array in Javascript

4

I'm a beginner, first and foremost.

A final challenge has been proposed in the Alura system in which you have to ask for 6 numbers for a user and draw 6, then compare the arrays to see how many were successful. It's a Mega Sena game.

I want to sort out 6 random numbers that DO NOT repeat. What I've been able to do so far is:

<meta charset="UTF-8">
<script>	
	var frase = function(texto) {
		document.write(texto + "<br>");
	}

	var sorteados = [];
	for(i = 0; i < 6 ; i++) {
		var sorteado = parseInt(Math.ceil(Math.random()*60));		
		sorteados.push();
		frase(sorteado);
	}
</script>

I would like to insert a if before each number insertion to check if it already exists in the array, but I have no idea how to do it. I guarantee that I have searched a lot, but nothing answers my question or is extremely complicated for a beginning user like me.

    
asked by anonymous 03.02.2015 / 14:15

2 answers

3

Solved elsewhere:

<script>	
	var frase = function(texto) {
		document.write(texto + "<br>");
	}

	var sorteados = [];
	while (sorteados.length < 6) {
		var novo = Math.round(Math.random() * 59) + 1;
		if (sorteados.indexOf(novo) == -1) {
			sorteados.push(novo);
			frase(novo);
		}
	}
</script>
    
03.02.2015 / 14:47
1

To check if a number exists in the array, simply use the method indexOf

if (sorteados.indexOf(sorteado) === -1) {
   // Insere o número pois ele não existe
}

indexOf will return -1 whenever there is no value in the array

To not repeat the numbers, you can do a recursive check!

In this case it will insert the 6 numbers, but never repeated

Example:

    var frase = function(texto) {
        document.write(texto + "<br>");
    }

       var sorteados = [];


      for(i = 0; i < 6 ; i++) {
          var sorteado = parseInt(Math.ceil(Math.random()*60));     

           // passa o array a ser incrementado e passa "frase" como callback para imprimir o número atual
          uniqueNumber(sorteados);

      }

    function uniqueNumber(array)
    {
    var number = parseInt(Math.ceil(Math.random()*60));

    // Insere se não existir
    if (array.indexOf(number) === -1) {
        array.push(number); 
        frase(sorteado);
    } else {
        console.log('repetiu');
        uniqueNumber(array);
    }

}

To ignore repeated numbers, leaving fewer numbers in case of repetition.

For example [1, 2, 3, 1] becomes [1, 2, 3] , just remove else from function uniqueNumber .

See an example on JSFIDDLE

    
03.02.2015 / 14:25