如何同时检查两个数组相同索引处的元素?

3
我想确定这两个数组中有多少项是匹配的,然后将其作为数字存储在状态中。
例如:
const [score, setScore] = React.useState(0)

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

我尝试过

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

如果可以,请解释为什么我的代码不能正常工作。


这回答你的问题吗?检查数组是否包含另一个数组的所有元素 - Heretic Monkey
如果您不介意使用一行代码,可以这样写:allCorrectAnswers.filter(ans => selections.includes(ans)).length - A1exandr Belan
3个回答

2

.map(无论是在顶级还是嵌套级别)都没有意义,因为您不是要将一个数组的每个元素转换为另一个数组。如果您想使用数组方法,请改用.reduce,并在回调中使用索引来访问另一个数组中的相关元素以查看它是否相等。

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

或者执行

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


使用我的代码,而不是修改它 - 因为您在循环内设置状态,所以您修改后的版本将无法正常工作。先计算出正确答案的总数,然后使用最终计算结果来设置状态。 - CertainPerformance
问题出在以错误的顺序回答问题时(例如先回答第二个问题,然后是第四个问题,再回答第一个问题...),正确的结果不会相加。 - agm
什么错误?没有问题的精确描述很难弄清楚事情。 - CertainPerformance
是的,那是我从Scrimba编辑器转移到Replit的想法。我移动了setScore但它没有工作,你能再检查一下吗? - agm
现在你没有在 Question.jsx 中调用 updateAnswers。根据 Stack Overflow 的准则,为了让问题在这里保持相关性,所有相关的代码都应该放在问题本身中 - 请努力做到这一点。 - CertainPerformance
显示剩余13条评论

0
首先,我建议使用Set来避免重复值,然后使用交集来查看匹配的元素。
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}

使用Set,您还可以提高性能,因为没有重复值。

这里是一个小基准测试。

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.

你的代码无法正常工作,因为你将答案(一个字符串)与一个项数组进行比较,结果始终为false。


-1
你可以使用 filter 方法和它的第二个参数 index。在你筛选出两个数组中所有匹配元素后,只需返回 length 属性,它将呈现匹配数量。

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


我更喜欢使用 forEach 或者 reduce。这种方法会分配一个可能非常巨大的数组 O(n) 的内存,只是为了在检查其长度后再将其丢弃。 - ggorlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接