How to compare 2 arrays and return the equal values within them?

Asked

Viewed 125 times

-1

  1. (INNER JOIN) Make an algorithm named after two players and then ask for 5 numbers from 1 to 10 for each player. First for player A and then for player B. After the choice of each player the algorithm must present which were the equal numbers that player A and B have placed. EX: Player A: 1, 2, 3, 4, 5 Player B : 1,2,3,8,7 Algorithm prints: 1,2,3
var rs = require('readline-sync')

    var a = []
    var b = []

    var nome1 = rs.question('Digite o nome do primeiro jogador : ')
    var nome2 = rs.question(' Digite o nome do segundo jogador : ')
    console.log('Digite 5 notas de 0 a 10 para o Primeiro jogador :')
    for(i = 5; i > 0 ; i--)

     { var nota = rs.questionInt('Nota : ')
     a.push(nota)

     }
     console.log(a)

     console.log('Digite 5 notas de 0 a 10 para o Segundo jogador :')
     for(i = 5; i > 0 ; i--)

     { var nota = rs.questionInt('Nota : ')
     b.push(nota)

     }
     console.log(b)

1 answer

1

Just compare what I ended up doing during the second increment. See if this fits you. Another thing, it would be interesting you replace the variable statement var for const or Let. In case your code would be const. Currently we no longer use the var as a matter of Hoisting.

var rs = require("readline-sync");

var a = [];
var b = [];
var repeated = [];

var nome1 = rs.question("Digite o nome do primeiro jogador : ");
var nome2 = rs.question(" Digite o nome do segundo jogador : ");

console.log("Digite 5 notas de 0 a 10 para o Primeiro jogador :");
for (i = 5; i > 0; i--) {
  var nota = rs.questionInt("Nota : ");
  a.push(nota);
}

console.log("Digite 5 notas de 0 a 10 para o Segundo jogador :");
for (i = 5; i > 0; i--) {
  var nota = rs.questionInt("Nota : ");
  if (a.includes(nota)) repeated.push(nota); // Adicionado aqui
  b.push(nota);
}

console.log("Items repetidos: ", repeated.join());
  • valeu rodou legal, I’m starting now but I’ll give a att in the variables to not use var more...

  • If I were to do the reverse, compare different numbers of A and B as I would?

Browser other questions tagged

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