How to query a data in an array in Javascript

Asked

Viewed 3,388 times

4

I’m a complete beginner, first of all.

A final challenge was proposed in the Alura system where you have to ask 6 numbers for a user and draw 6, then compare the arrays to see how much were hit. It’s a Mega Sena game.

I want to draw 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 I’ve searched a lot, but nothing answers my question or is extremely complicated for a novice user like me.

2 answers

3

They fixed me up somewhere else:

<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>

1

To check if a number exists in the array, just 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 he will enter 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] become [1, 2, 3], just remove the else of function uniqueNumber.

See an example on JSFIDDLE

  • 1

    This answers the question, but it is worth noting that if a number already exists it will not insert, but continue the iteration in the loop resulting in a number less at the end of the array.

  • Thanks for the answer. .

  • Oops! sorry. Updated. I forgot to deal with the function that writes the text! The function frase should be within the verification whether or not that number already exists, within uniqueNumber

Browser other questions tagged

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