Have a 2d array (Arr1) and not able to get a check/compare against another 2d array (Arr2) to count arrays what match with exact elements. for example:
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));
Return should be true, false, true
or just 1, 0, 1
, so in the end can count amount of true or 1
, expected outcome: true===2
Any good way to do that without using for loops?
Advertisement
Answer
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));