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 2Lo 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.
.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);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.
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);