Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
¿Cómo puedo verificar dos matrices en el mismo índice?

Quiero determinar cuántos de los elementos en estas dos matrices coinciden, luego almacenarlo en el estado como un número.

Por ejemplo

 const [score, setScore] = React.useState(0) const selections = ["one", "two", "three"] const allCorrectAnswers = ["four", "two", "three"] // this should return 2

Lo intenté

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

Explique por qué mi código no funciona tan bien si puede.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

.map (ya sea en el nivel superior o anidado) no tiene sentido, porque no está tratando de transformar cada elemento de una matriz en otra. Si desea usar un método de matriz, use .reduce en su lugar y use el índice en la devolución de llamada para acceder al elemento asociado en la otra matriz para ver si es igual.

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

o hacer

 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 Report

0

En primer lugar, sugeriría usar un Conjunto para evitar valores duplicados y luego una intersección para ver qué elemento coincide.

 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}

Usando Set, también mejorará el rendimiento ya que no hay valores duplicados.

Aquí hay un pequeño punto de referencia

 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.

Su código no funciona ya que compara la respuesta (una cadena) con una matriz de elementos que terminan siendo siempre falsos.

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar el método de filter y su segundo parámetro que es index . Después de filtrar todos los elementos que coinciden en dos matrices, puede devolver la propiedad de length que presentará el número de coincidencias.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!