Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
How can I check two arrays at the same index?

I want to determine how many of the items in these two arrays match, then store that in state as a number.

For example

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2

I tried

function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer) 
      ? setScore(prevScore => prevScore + 1) : 0
  )
}

Please explain why my code isn't working as well if you can.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

.map (either at the top level or the nested one) doesn't make sense, because you aren't trying to transform each element of one array into another. If you want to use an array method, use .reduce instead, and use the index in the callback to access the associated element in the other array to see if it's equal.

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const totalCorrect = selections.reduce(
  (correctSoFar, answer, i) => correctSoFar + (answer === allCorrectAnswers[i]),
  0
);
console.log(totalCorrect);
// setScore(totalCorrect);

or do

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

let totalCorrect = 0;
selections.forEach((answer, i) => {
  if (answer === allCorrectAnswers[i]) {
    totalCorrect++;
  }
});
console.log(totalCorrect);
// setScore(totalCorrect);

about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, I would suggest to use a Set to avoid duplicate values and then an intersection to see what element matches.

const a = new Set([1,2,3]);
const b = new Set([4,3,2]);
const intersection = new Set([...a].filter(x => b.has(x)));
    // {2,3}

Using Set, you will also improve performance since there is no duplicate values.

Here is a small benchmark

Checked test: Javascript Set intersection x 70,358 ops/sec ±2.26% (61 runs sampled)
Checked test: Javascript Array intersection x 40,687 ops/sec ±1.22% (67 runs sampled)
Success! Validation completed.

Your code does not work since you comparing the answer (a string) with an array of item which end up to be always false.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use filter method and its second parameter that is index. After you filter for all elements that match in two arrays, you can just return the length property witch will present the number of matches.

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

const checkSelectedAnswer = (selections, allCorrectAnswers) => selections.filter((eachChoice,index) => eachChoice === allCorrectAnswers[index]).length;

const numberOfCorrectAnswers = checkSelectedAnswer(selections, allCorrectAnswers);
console.log(numberOfCorrectAnswers);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda