通过检查具有相同元素的数组,将二维数组与另一个二维数组进行比较

时间:2021-06-19 13:48:01

标签: javascript typescript

有一个二维数组 (Arr1) 并且无法检查/比较另一个二维数组 (Arr2) 以计算与精确元素匹配的数组。 例如:

const arr1: string[][] = [
  ["R", "P"],
  ["R", "S"],
  ["S", "P"],
];
const checkAgainst: string[][] = [
  ["R", "S"],
  ["P", "R"],
  ["S", "P"],
];

function check(arr1: string[][]) {
  arr1.map((a, index, arr) => {
    let result = arr[0].filter((o1) =>
      checkAgainst.some((o2) => o1.id === o2.id)
    );
  });
}
console.log(check(arr1));

返回应该是true, false, true或者只是1, 0, 1,所以最后可以计算true or 1的数量,预期结果:true===2

有什么好方法可以使用 for 循环来做到这一点?

1 个答案:

答案 0 :(得分:2)

function haveSameValues(arr1: string[], arr2: string[]): boolean {
  if (arr1.length === 0 || arr1.length != arr2.length) {
    return false;
  }

  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] != arr2[i]) {
      return false;
    }
  }

  return true;
}

function countMatches(matrix1: string[][], matrix2: string[][]): number {
  let count = 0;

  for (const arr1 of matrix1) {
    for (const arr2 of matrix2) {
      if (haveSameValues(arr1, arr2) {
        count++;
      }
    }
  }

  return count;
}

const arr1: string[][] = [
  ["R", "P"],
  ["R", "S"],
  ["S", "P"],
];
const checkAgainst: string[][] = [
  ["R", "S"],
  ["P", "R"],
  ["S", "P"],
];

console.log(countMatches(arr1, checkAgainst));