Compare values between Array's JavaScript

-2

Good morning, My dear, I need an orientation on comparing values between two Array's in JavaScript. I am working on a small lottery simulator where the code starts with the first Array containing 6 numbers, the second Array will store the 6 numbers entered by the user.

At this point everything ok, however, you need to compare the two Arrays and print how many and which numbers were successful. Can anyone give me strength at that point in the code. Thank you in advance for your attention.

    
asked by anonymous 27.12.2017 / 14:03

1 answer

1

Just scroll through one of the arrays, checking in the other if each number of the first one is present in it. The numbers that hit you can be stored in a third array.

There are several ways to do this, here is the most basic example, which uses a for loop (there is a more elegant way, but this is the most traditional and logic goes for many other languages):

var jogo = [5, 15, 25, 35, 45, 55];
var sorteio = [9, 15, 16, 21, 35, 49];
var acertos = [];

// Verifica se cada número jogado
// está na lista dos sorteados
for(var i=0; i<jogo.length; i++) {
    if(sorteio.indexOf(jogo[i]) > -1) {
        acertos.push(jogo[i]);
    }
}

console.log("Você acertou " + acertos.length + " números: ", acertos);
    
27.12.2017 / 14:43