Compare values between Array’s Javascript

Asked

Viewed 5,868 times

-1

Good morning, My dear, I need some guidance on comparing values between two Array’s in Javascript. I am working on small lottery simulator where the code starts with the first Array containing 6 numbers, the second Array will store the 6 numbers reported by the user.

Up to this point everything ok, however, it is necessary to compare the two Arrays and print out how many and which numbers were hit. I wonder if someone could give me a boost at this point in the code. Thank you in advance for all your attention.

  • https://www.devmedia.com.br/for-em-javascript-dica/28554

  • Olpa Jeferson, when you have a question about something try posting the part of the code you did and what you’ve already researched, vague questions will have vague answers

3 answers

6


Just go 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 store in a third array.

There are several ways to do this, follow the most basic example, which uses a loop for (there are more elegant ways, but this is the most traditional and the 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);

  • Thank you very much, that’s what I was looking for.... m/

2

With the new Javascript templates, you can get the expected result using the method filter():

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

sorteio.filter(function(element) {
  if (jogo.indexOf(element) !== -1) {   // se for encontrado um valor nos dois arrays
    acertos.push(element)
  }
});

console.log('Os números que você acertou foram: ', acertos)

As well as the method includes()

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

sorteio.filter(function(element) {
  if (jogo.includes(element)) {   // se for encontrado um valor nos dois arrays
    acertos.push(element)
  }
});

console.log('Os números que você acertou foram: ', acertos)

2

I found a slightly simpler way to use the filter for this purpose.

The Array.prototype.includes() check whether or not the item exists in the array and returns a Boolean.

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

const acertos = sorteio.filter(numero => jogo.includes(numero))


console.log("Você acertou " + acertos.length + " números: ", acertos)

Browser other questions tagged

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