JavaScript中的数组交集

我很困惑,这个问题促使我用JavaScript编写一个函数,该函数计算两个数组并返回两个数组包含多少个匹配项的数值。似乎很简单,但是在函数中编写了循环之后,我不确定该去哪里。

这是我写的:

function gradeQuiz(studentAnswers, teacherAnswers) {
  for (let i = 0; i < studentAnswers.length; i++) {
    let student = studentAnswers[i]
  for (let x = 0; x < teacherAnswers.length; x++) {
    let teacher = teacherAnswers[x]

  }
  }
  }

  gradeQuiz(["C","D","B"],["C","A","B"])
评论
小辣条
小辣条
var array1 = ["string", "otherString"];
var array2 = ["string", "string"];

function matches(arr1, arr2) {
  var matches = 0; // Number of matches starts at 0
  // This will go over every 'combination' of values to look for matches
  arr1.forEach(item => { // For each item in the first array
    arr2.forEach(item2 => { // For each item in the second array
      if (item === item2) { // If the items match, add 1 to the counter
        matches += 1;
      }
    });
  });
  return matches // Once it's finished return how many matches there were
}
console.log(matches(array1, array2)); // Log it to the console so we can see

这将遍历两个数组中的每个项目以检查是否匹配。这是一个简单的功能,但是可以工作。注意,这不仅适用于字符串;它适用于任何可以比较的类型。

点赞
评论